- 一、互斥锁
- 1.1互斥锁是什么?
- 1.2互斥锁参数介绍
- 1.3互斥锁案例
- 二、读写锁
- 2.1读写锁是什么?
- 2.2读写锁函数介绍
- 2.3读写锁案例
- 总结
一、互斥锁 1.1互斥锁是什么?
1.2互斥锁参数介绍 1.3互斥锁案例在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。
#include二、读写锁 2.1读写锁是什么?#include #include //全局变量,所有的线程都共享这一份资源 int titckets=1000; //创建一个互斥量 pthread_mutex_t mutex; void* sellticket(void* arg) { //加锁 //pthread_mutex_lock(&mutex); //卖票 while(1) { //加锁 pthread_mutex_lock(&mutex); if(titckets>0) { usleep(3000); printf("%ld 正在卖第%d张门票n",pthread_self(),titckets); titckets--; }else { pthread_mutex_unlock(&mutex); break; } //解锁 pthread_mutex_unlock(&mutex); } //解锁 //pthread_mutex_unlock(&mutex); return NULL; } int main() { //初始化互斥量 pthread_mutex_init(&mutex,NULL); //创建3个子线程 pthread_t tid[3]; for(int i=0;i<3;i++) { pthread_create(&tid[i],NULL,sellticket,NULL); } //设置线程分离 for(int i=0;i<3;i++) { pthread_detach(tid[i]); } pthread_exit(NULL);//退出主线程 //释放互斥量资源 pthread_mutex_destroy(&mutex); return 0; }
2.2读写锁函数介绍 2.3读写锁案例读写锁实际是一种特殊的自旋锁,它把对共享资源的访问者划分成读者和写者,读者只对共享资源进行读访问,写者则需要对共享资源进行写操作。
#include#include #include //创建一个共享数据 int num=1; //pthread_mutex_t mutex; pthread_rwlock_t rwlock; void* writenum(void* arg) { while(1) { //pthread_mutex_lock(&mutex); pthread_rwlock_wrlock(&rwlock); num++; printf("++write:tid:%ld,num: %dn",pthread_self(),num); //pthread_mutex_unlock(&mutex); pthread_rwlock_unlock(&rwlock); usleep(100); } return NULL; } void* readnum(void* arg) { while(1) { //pthread_mutex_lock(&mutex); pthread_rwlock_rdlock(&rwlock); printf("==read,tid:%ld,num: %dn",pthread_self(),num); //pthread_mutex_unlock(&mutex); pthread_rwlock_unlock(&rwlock); usleep(100); } return NULL; } int main() { //pthread_mutex_init(&mutex,NULL); pthread_rwlock_init(&rwlock,NULL); //创建3个写线程 pthread_t wtid[3]; for(int i=0;i<3;i++) { pthread_create(&wtid[i],NULL,writenum,NULL); } //创建5个读线程 pthread_t rtid[5]; for(int i=0;i<5;i++) { pthread_create(&rtid[i],NULL,readnum,NULL); } for(int i=0;i<3;i++) { pthread_detach(wtid[i]); } for(int i=0;i<5;i++) { pthread_detach(rtid[i]); } pthread_exit(NULL); //pthread_mutex_destroy(&mutex); pthread_rwlock_destroy(&rwlock); return 0; }
总结
今天主要介绍互斥锁和读写锁,他们分别用在不同的场景。



