Cobar Client的使用

article/2025/9/17 16:53:05

cobar client是出自阿里的产品,cobar client只需要引入jar包即可,不需要建立服务。下面的地址是cobar client的帮助文档

http://code.alibabatech.com/docs/cobarclient/zh/

http://www.kuqin.com/system-analysis/20120212/318089.html

分库分表都是在Cobar产品里面的,Cobar分为两类,分别是Cobar Client和Cobar Server,根据业务的需要进行选择,Cobar Server是一组独立的(Stand Alone)的Server集群,Cobar Client就是第三方的Java包,他就直接嵌入到应用上面去。然后他的拆分规则都是直接写到应用的配置文件里面的。这是阿里自主开发的,没有用到外面的一些开源的工具

用到的数据库创建语句:

create database dbtest1;
create database dbtest2;
create database dbtest3;//分别在这三个数据库中创建下面的表:
CREATE TABLE `cont` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`taobaoId` bigint(20) DEFAULT '0',`name` varchar(20) DEFAULT '',`upd_time` datetime DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

cobar是扩展ibatis的 SqlMapClientTemplate的功能,对分布在多个数据库的表进行路由读写的开源软件。但是不支持单库的多表操作。

以下贴出一些关键的代码,详细的可以下载功能进行运行查看:

工程截图:


下面列举一个简单的功能,就spring与ibatis进行整合,在mysql数据库上面进行操作,对cont表进行添加和查询的功能操作:

简单看下service,dao的文件代码

Service:

public interface ContService {/*** 基本插入* * @return*/public Long addCont(Cont cont);/*** 根据主键查询*/public Cont getContByKey(Long id);/*** 根据条件查询* * @param contQuery*            查询条件* @return*/public List<Cont> getContList(ContQuery contQuery);
}

ServiceImpl:

@Service("contService")
public class ContServiceImpl implements ContService {private static final Log log = LogFactory.getLog(ContServiceImpl.class);@ResourceContDAO contDAO;/*** 插入数据库* * @return*/public Long addCont(Cont cont) {try {return contDAO.addCont(cont);} catch (SQLException e) {log.error("dao addCont error.:" + e.getMessage(), e);}return 0L;}/*** 根据主键查找*/public Cont getContByKey(Long id) {try {return contDAO.getContByKey(id);} catch (SQLException e) {log.error("dao getContbyKey error.:" + e.getMessage(), e);}return null;}public List<Cont> getContList(ContQuery contQuery) {try {return contDAO.getContList(contQuery);} catch (SQLException e) {log.error("get Cont list error." + e.getMessage(), e);}return Collections.emptyList();}}

Dao:

@Repository
public class ContDAO {@ResourceSqlMapClientTemplate sqlMapClientTemplate;public Long addCont(Cont cont) throws SQLException {return (Long) this.sqlMapClientTemplate.insert("Cont.insertCont", cont);}/*** 根据主键查找* * @throws SQLException*/public Cont getContByKey(Long id) throws SQLException {Map<String, Object> params = new HashMap<String, Object>();params.put("id", id);Cont result = (Cont) this.sqlMapClientTemplate.queryForObject("Cont.getContByKey", params);return result;}@SuppressWarnings("unchecked")public List<Cont> getContList(ContQuery contQuery) throws SQLException {if (contQuery.getFields() != null && contQuery.getFields() != "") {return (List<Cont>) this.sqlMapClientTemplate.queryForList("Cont.getContListFields", contQuery);}return (List<Cont>) this.sqlMapClientTemplate.queryForList("Cont.getContList", contQuery);}}


1、下面applicationContext.xmlspring配置文件是针对没有在cobar的情况下进行的常规配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"default-lazy-init="false"><description>Spring公共配置</description><context:component-scan base-package="com.hj.cobar"></context:component-scan><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>application.development.properties</value></property></bean><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><!-- 基本属性 url、user、password --><property name="url" value="${jdbc_url}"/><property name="username" value="${jdbc_user}"/><property name="password" value="${jdbc_password}"/><!-- 配置初始化大小、最小、最大 --><property name="initialSize" value="1"/><property name="minIdle" value="1"/><property name="maxActive" value="20"/><!-- 配置获取连接等待超时的时间 --><property name="maxWait" value="60000"/><!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --><property name="timeBetweenEvictionRunsMillis" value="60000"/><!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --><property name="minEvictableIdleTimeMillis" value="300000"/><property name="validationQuery" value="SELECT 'x'"/><property name="testWhileIdle" value="true"/><property name="testOnBorrow" value="false"/><property name="testOnReturn" value="false"/><!-- 打开PSCache,并且指定每个连接上PSCache的大小 --><property name="poolPreparedStatements" value="false"/><property name="maxPoolPreparedStatementPerConnectionSize" value="20"/><!-- 配置监控统计拦截的filters --><property name="filters" value="stat"/></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!-- 使用annotation定义事务 --><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/><!-- 配置ibatis的SqlMapClient --><bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"><property name="dataSource" ref="dataSource" />  <property name="configLocation"><value>classpath:/sqlmap-config.xml</value></property></bean><bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"><property name="sqlMapClient" ref="sqlMapClient" />  </bean></beans>

2、下面是在applicationContext.xml使用cobar的配置,一些细节可参考阿里的cobar的帮助文档:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd"default-lazy-init="false"><description>Spring公共配置</description><context:component-scan base-package="com.hj.cobar"></context:component-scan><bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>application.development.properties</value></property></bean><!-- 配置数据源开始 --><bean id="dataSources" class="com.alibaba.cobar.client.datasources.DefaultCobarDataSourceService"><property name="dataSourceDescriptors"><set><bean class="com.alibaba.cobar.client.datasources.CobarDataSourceDescriptor"><property name="identity" value="partition0"/><property name="targetDataSource" ref="dataSource0"/><property name="targetDetectorDataSource" ref="dataSource0"/></bean><bean class="com.alibaba.cobar.client.datasources.CobarDataSourceDescriptor"><property name="identity" value="partition1"/><property name="targetDataSource" ref="dataSource1"/><property name="targetDetectorDataSource" ref="dataSource1"/></bean><bean class="com.alibaba.cobar.client.datasources.CobarDataSourceDescriptor"><property name="identity" value="partition2"/><property name="targetDataSource" ref="dataSource2"/><property name="targetDetectorDataSource" ref="dataSource2"/></bean></set></property><property name="haDataSourceCreator"><bean class="com.alibaba.cobar.client.datasources.ha.FailoverHotSwapDataSourceCreator"><property name="detectingSql" value="update cobarha set timeflag=CURRENT_TIMESTAMP()"/></bean></property></bean><!-- 数据源0 --><bean id="dataSource0" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc0.url}" /><property name="username" value="${jdbc0.username}" /><property name="password" value="${jdbc0.password}" /><property name="filters" value="config" /><property name="maxActive" value="5" /><property name="initialSize" value="5" /><property name="maxWait" value="1" /><property name="minIdle" value="5" /><property name="timeBetweenEvictionRunsMillis" value="3000" /><property name="minEvictableIdleTimeMillis" value="300000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><property name="poolPreparedStatements" value="true" /><property name="maxPoolPreparedStatementPerConnectionSize" value="20" /><!-- <property name="connectionProperties" value="config.decrypt=true" /> --></bean><!-- 数据源1 --><bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc1.url}" /><property name="username" value="${jdbc1.username}" /><property name="password" value="${jdbc1.password}" /><property name="filters" value="config" /><property name="maxActive" value="5" /><property name="initialSize" value="5" /><property name="maxWait" value="1" /><property name="minIdle" value="5" /><property name="timeBetweenEvictionRunsMillis" value="3000" /><property name="minEvictableIdleTimeMillis" value="300000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><property name="poolPreparedStatements" value="true" /><property name="maxPoolPreparedStatementPerConnectionSize" value="20" /></bean><!-- 数据源2 --><bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc2.url}" /><property name="username" value="${jdbc2.username}" /><property name="password" value="${jdbc2.password}" /><property name="filters" value="config" /><property name="maxActive" value="5" /><property name="initialSize" value="5" /><property name="maxWait" value="1" /><property name="minIdle" value="5" /><property name="timeBetweenEvictionRunsMillis" value="3000" /><property name="minEvictableIdleTimeMillis" value="300000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><property name="poolPreparedStatements" value="true" /><property name="maxPoolPreparedStatementPerConnectionSize" value="20" /></bean>
<!-- 配置数据源结束 -->	<!-- 配置路由规则开始 --><bean id="hashFunction" class="com.hj.cobar.dao.router.HashFunction"></bean><bean id="internalRouter"class="com.alibaba.cobar.client.router.config.CobarInteralRouterXmlFactoryBean"><!-- functionsMap是在使用自定义路由规则函数的时候使用 --><property name="functionsMap"><map><entry key="hash" value-ref="hashFunction"></entry></map></property><property name="configLocations"><list><value>classpath:/dbRule/sharding-rules-on-namespace.xml</value></list></property></bean>
<!-- 配置路由规则结束 -->  <!-- 事务配置 --><bean id="transactionManager" class="com.alibaba.cobar.client.transaction.MultipleDataSourcesTransactionManager"><property name="cobarDataSourceService" ref="dataSources"/></bean><!-- 使用annotation定义事务 --><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/><!--  iBatis SQL map定义。                                                    --><bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"><!-- 这里配置的dataSource0为默认的数据源,如果找不到数据库的话则到该数据源中查找 --><property name="dataSource" ref="dataSource0" />  <property name="configLocation"><value>classpath:/sqlmap-config.xml</value></property></bean><!-- 工程里一定要使用此工程模板,不能再使用ibatis原生的api,不然有的情况会不经过cobar的过滤 --><bean id="sqlMapClientTemplate" class="com.alibaba.cobar.client.CobarSqlMapClientTemplate"><property name="sqlMapClient" ref="sqlMapClient" /><property name="cobarDataSourceService" ref="dataSources" /><property name="router" ref="internalRouter" /><property name="sqlAuditor"><bean class="com.alibaba.cobar.client.audit.SimpleSqlAuditor" /></property><property name="profileLongTimeRunningSql" value="true" /><property name="longTimeRunningSqlIntervalThreshold" value="3600000" /></bean></beans>

3、在sharding-rules-on-namespace.xml配置cobar的路由规则,因为此路由规则是使用自定义的路由规则,所以还要写一个自定义的规则函数类

<rules><rule><namespace>Cont</namespace><!-- 表达式如果不使用自定义路由规则函数,而是直接使用   taobaoId%2==0这种的话就不用在文件中配置<property name="functionsMap">中了--><shardingExpression>hash.apply(taobaoId) == 0</shardingExpression><shards>partition0</shards></rule><rule><namespace>Cont</namespace><shardingExpression>hash.apply(taobaoId) == 1</shardingExpression><shards>partition1</shards></rule><rule><namespace>Cont</namespace><shardingExpression>hash.apply(taobaoId) == 2</shardingExpression><shards>partition2</shards></rule></rules>

4、自定义的路由规则函数类

hash的一种做法是对taobaoId进行md5加密,然后取前几位(我们这里取前两位),然后就可以将不同的taobaoId哈希到不同的用户表(cont_xx)中了。

通过这个技巧,我们可以将不同的taobaoId分散到256中用户表中,分别是cont_00,user_01 ...... cont_ff。因为taobaoId是数字且递增,根据md5的算法,可以将用户数据几乎很均匀的分别到不同的cont表中。

但是这里有个问题是,如果我们的系统的数据越来越多,势必单张表的数据量越来越大,而且根据这种算法无法扩展表,这又会回到单表量大的问题。

下面只是简单的用求余的方法来返回值

/*** 根据某种自定义的hash算法来进行散列,并根据散列的值进行路由*  常见的水平切分规则有:基于范围的切分, 比如 memberId > 10000 and memberId < 20000基于模数的切分, 比如 memberId%128==1 或者 memberId%128==2 或者...基于哈希(hashing)的切分, 比如hashing(memberId)==someValue等* @author hj**/
public class HashFunction{/*** 对三个数据库进行散列分布* 1、返回其他值,没有在配置文件中配置的,如负数等,在默认数据库中查找* 2、比如现在配置文件中配置有三个结果进行散列,如果返回为0,那么apply方法只调用一次,如果返回为2,*   那么apply方法就会被调用三次,也就是每次是按照配置文件的顺序依次的调用方法进行判断结果,而不会缓存方法返回值进行判断* @param taobaoId* @return*/public int apply(Long taobaoId) {//先从缓存获取 没有则查询数据库//input 可能是taobaoId,拿taobaoId到缓存里去查用户的DB坐标信息。然后把库的编号输出System.out.println("taobaoId:"+taobaoId);int result = (int)(taobaoId % 3);System.out.println("在第"+(result + 1)+"个数据库中");return result;}/**注:只调用一次taobaoId:3354在第1个数据库中注:调用了三次taobaoId:7043在第3个数据库中taobaoId:7043在第3个数据库中taobaoId:7043在第3个数据库中*/}

5、下面是对service的单元测试

/*** cobar的单元测试*/
public class AppTest extends TestCase{ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");ContService contService = (ContService) context.getBean("contService");/*** 没有使用对象查询直接使用基本类型则到默认的数据源中去查找数据*/public void test1(){Cont cont = contService.getContByKey(2L);System.out.println(cont);}/*** 测试添加*/public void test2(){Cont cont = new Cont();cont.setName("gd");Long taobaoId = new Long(new Random().nextInt(10000));System.out.println("#"+taobaoId);cont.setTaobaoId(taobaoId);contService.addCont(cont);}/*** 测试使用对象包含taobaoId属性的进行查找* 使用这种方式可以根据taobaoId分库查找*/public void test3(){ContQuery contQuery = new ContQuery();contQuery.setTaobaoId(2809L);List<Cont> list = contService.getContList(contQuery);if(list != null){System.out.println(list.get(0));}}
}

工程下载地址: http://download.csdn.net/detail/wxwzy738/6698067



http://chatgpt.dhexx.cn/article/xUbmwnDV.shtml

相关文章

Cobar介绍

概述 Cobar是关系型数据的分布式处理系统&#xff0c;它可以在分布式的环境下看上去像传统数据库一样为您提供海量数据服务。 产品在阿里巴巴B2B公司已经稳定运行了3年以上。目前已经接管了3000个MySQL数据库的schema&#xff0c;为应用提供数据服务。据最近统计cobar集群目前…

[存储] Cobar使用文档(可用作MySQL大型集群解决方案)

最近好不容易抽空研究了下Cobar&#xff0c;感觉这个产品确实很不错&#xff08;在文档方面比Amoeba强多了&#xff09;&#xff0c;特此推荐给大家。Cobar是阿里巴巴研发的关系型数据的分布式处理系统&#xff0c;该产品成功替代了原先基于Oracle的数据存储方案&#xff0c;目…

Linux nohup命令用法详解

nohup 英文全称 no hang up&#xff08;不挂起&#xff09;&#xff0c;用于在系统后台不挂断地运行命令&#xff0c;退出终端不会影响程序的运行。 nohup 命令&#xff0c;在默认情况下&#xff08;非重定向时&#xff09;&#xff0c;会输出一个名叫 nohup.out 的文件到当前…

Linux nohup 命令

1.简介 nohup 英文全称 no hang up&#xff08;不挂起&#xff09;&#xff0c;用于在系统后台不挂断地运行命令&#xff0c;退出终端不会影响程序的运行。 nohup 命令&#xff0c;在默认情况下&#xff08;非重定向时&#xff09;&#xff0c;会输出一个名叫 nohup.out 的文…

【nohup】nohup命令的简单使用

文章目录 1 nohup时2 nohup后 1 nohup时 执行下方命令后&#xff0c;将 标准输出(1&#xff0c;默认可不写)、错误信息(2) 写入到 output.log 文件中。 nohup python train.py >output.log 2>&1 & nohup hb_mapper makertbin -c xx.yaml --model-type onnx 2&g…

【学习笔记】Windows 下线程同步之互斥锁

目录 前言环境简介相关函数CreateMutexWait 函数ReleaseMutexCloseHandle 其他互斥锁的名字未命名互斥锁的同步互斥锁的意外终止临界区对象 示例参考 前言 本文所涉及的同步主要描述在 Windows 环境下的机制&#xff0c;和 Linux 中的同步机制有一定的联系&#xff0c;但注意并…

C++——互斥量

文章目录 一、基本知识二、独占互斥量mutex1.mutex的介绍2.mutex的成员函数3.实例演示 三、lock_guard和unique_lock的使用和区别四、递归互斥量recursive_mutex1.基本知识2.演示示例 五、带超时的互斥量std::timed_mutex和std::recursive_timed_mutex 一、基本知识 C11提供如…

Linux——什么是互斥与互斥锁

目录 一.前提&#xff1a;临界区 & 临界资源 二.什么是互斥 &#xff08;一&#xff09;.互斥概念 &#xff08;二&#xff09;.为什么需要互斥 三.互斥锁介绍 &#xff08;一&#xff09;.互斥锁的概念 &#xff08;二&#xff09;.互斥锁的使用 ①系统API接口 ②…

线程的互斥与同步

线程的互斥与同步 线程的互斥简单的抢票程序互斥量初始化互斥量销毁互斥量互斥量加锁和解锁 互斥量实现原理 可重入VS线程安全概念常见的线程不安全的情况常见的线程安全的情况常见不可重入的情况常见可重入的情况可重入与线程安全联系可重入与线程安全区别 死锁死锁四个必要条…

FreeRTOS个人笔记-互斥量

根据个人的学习方向&#xff0c;学习FreeRTOS。由于野火小哥把FreeRTOS讲得比较含蓄&#xff0c;打算在本专栏尽量细化一点。作为个人笔记&#xff0c;仅供参考或查阅。 配套资料&#xff1a;FreeRTOS内核实现与应用开发实战指南、野火FreeRTOS配套视频源码、b站野火FreeRTOS视…

C++ 互斥锁原理以及实际使用介绍

兄弟姐妹们&#xff0c;我又回来了&#xff0c;今天带来实际开发中都需要使用的互斥锁的内容&#xff0c;主要聊一聊如何使用互斥锁以及都有哪几种方式实现互斥锁。实现互斥&#xff0c;可以有以下几种方式&#xff1a;互斥量&#xff08;Mutex&#xff09;、递归互斥量&#x…

MySQL mutex互斥锁

在事务机制中&#xff0c;锁机制是为了保证高并发&#xff0c;数据一致性的重要实现方式。MySQL除了Innodb引擎层面的行锁&#xff0c;还有latch锁。latch锁的作用资源协调处理。包含表句柄&#xff0c;线程&#xff0c;cpu线程&#xff0c;内存池等。其保证非常短时间内快速处…

uCOSii中的互斥信号量

uCOSii中的互斥信号量 一、互斥型信号量项管理 (MUTUAL EXCLUSION SEMAPHORE MANAGEMENT) OSMutexAccept() 无条件等待地获取互斥型信号量 OSMutexCreate() 建立并初始化一个互斥型信号量 OSMutexDel() 删除互斥型信号量 OSMutexPend() 等待一个互斥型信号量 OSMutexPost…

互斥信号量

目录 1、Creat 2、Delete 3、Wait 4、Post 5、Statu 互斥信号量 在介绍二进制信号量时&#xff0c;曾讨论到如果二进制信号量创建时设置参数 bInitValue 为TRUE&#xff0c;则可以用于互斥访问共享资源。实际上&#xff0c;SylixOS 的二进制信号量实现的互斥性是将一个变量…

UCOS-III 互斥量

互斥量 一、互斥量基本概念二、互斥量优先级继承机制三、互斥量应用场景四、互斥量运作机制五、互斥量创建流程1、定义互斥量2、创建互斥量 六、互斥量接口函数1、创建互斥量函数OSMutexCreate()2、删除互斥量函数 OSMutexDel()3、获取互斥量函数 OSMutexPend()4、释放互斥量函…

互斥量知识

文章目录 互斥量1、基本概念2、互斥量的优先级继承机制3、互斥量应用场景4、互斥量运行机制5、互斥量控制块6、互斥量函数接口&#xff08;1&#xff09;互斥量创建函数 xSemaphoreCreateMutex()&#xff08;2&#xff09;递归互斥量创建函数 xSemaphoreCreateRecursiveMutex()…

同步和互斥

同步和互斥 竞争与协作 在单核 CPU 系统里&#xff0c;为了实现多个程序同时运行的假象&#xff0c;操作系统通常以时间片调度的方式&#xff0c;让每个进程执行每次执行一个时间片&#xff0c;时间片用完了&#xff0c;就切换下一个进程运行&#xff0c;由于这个时间片的时间很…

多线程的同步与互斥(互斥锁、条件变量、读写锁、自旋锁、信号量)

文章目录 一、同步与互斥的概念二、互斥锁&#xff08;同步&#xff09;三、条件变量&#xff08;同步&#xff09;1、线程的条件变量实例12、线程的条件变量实例23、虚假唤醒(spurious wakeup) 四、读写锁&#xff08;同步&#xff09;五、自旋锁&#xff08;同步&#xff09;…

同步和互斥区别

互斥的概念 由于多线程执行操作共享变量的这段代码可能会导致竞争状态&#xff0c;因此我们将此段代码称为临界区&#xff08;critical section&#xff09;&#xff0c;它是访问共享资源的代码片段&#xff0c;一定不能给多线程同时执行。 我们希望这段代码是互斥&#xff0…

操作系统——互斥的定义及实现

一、进程互斥的定义 所谓进程互斥,指的是对某个系统资源,一个进程正在使用它,另外一个想用它的进程就必须等待,而不能同时使用 。进程互斥是多道程序系统中进程间存在的一种源于资源共享的制约关系,也称间接制约关系,主要是由被共享资源的使用性质所决定的。 二、互斥…