Linux学习之多线程编程(线程的同步)

言之者无罪,闻之者足以戒。 ——《诗序》

(三)、线程的同步

1、互斥量

当多个线程共享相同的内存时,需要每一个线程看到相同的视图。当一个线程修改变量时,而其他线程也可以读取或者修改这个变量,就需要对这些线程同步,确保他们不会访问到无效的变量。

在变量修改时间多于一个存储器访问周期的处理器结构中,当存储器的读和写这两个周期交叉时,这种潜在的不一致性就会出现。当然这与处理器相关,但是在可移植的程序中并不能对处理器做出任何假设。


 
 
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <signal.h>
  7. #include <errno.h>
  8. //创建一个结构体,数据类型都一样是为了方便赋值
  9. struct student
  10. {
  11. int id;
  12. int age;
  13. int name;
  14. }stu;
  15. int i;
  16. void *thread_fun1(void *arg)
  17. {
  18. while( 1)
  19. {
  20. //对结构体变量赋值
  21. stu.id = i;
  22. stu.age = i;
  23. stu.name = i;
  24. i++;
  25. if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
  26. {
  27. printf( "thread 1 %d,%d,%d\n", stu.id, stu.age, stu.name);
  28. break;
  29. }
  30. }
  31. return ( void *) 0;
  32. }
  33. void *thread_fun2(void *arg)
  34. {
  35. while( 1)
  36. {
  37. stu.id = i;
  38. stu.age = i;
  39. stu.name = i;
  40. i++;
  41. if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
  42. {
  43. printf( "thread 2 %d,%d,%d\n", stu.id, stu.age, stu.name);
  44. break;
  45. }
  46. }
  47. return ( void *) 0;
  48. }
  49. int main()
  50. {
  51. pthread_t tid1,tid2;
  52. int err;
  53. //创建新的线程
  54. err = pthread_create(&tid1, NULL,thread_fun1, NULL);
  55. if(err != 0)
  56. {
  57. printf( "create new thread failure\n");
  58. return;
  59. }
  60. err = pthread_create(&tid1, NULL,thread_fun1, NULL);
  61. if(err != 0)
  62. {
  63. printf( "create new thread failure\n");
  64. return;
  65. }
  66. //等待新的线程运行结束
  67. pthread_join(tid1, NULL);
  68. pthread_join(tid2, NULL);
  69. return 0;
  70. }

为了让线程访问数据不产生冲突,这要就需要对变量加锁,使得同一时刻只有一个线程可以访问变量。互斥量本质就是锁,访问共享资源前对互斥量加锁,访问完成后解锁。

当互斥量加锁以后,其他所有需要访问该互斥量的线程都将阻塞。

当互斥量解锁以后,所有因为这个互斥量阻塞的线程都将变为就绪态,第一个获得cpu的线程会获得互斥量,变为运行态,而其他线程会继续变为阻塞,在这种方式下访问互斥量每次只有一个线程能向前执行。

互斥量用pthread_mutex_t类型的数据表示,在使用之前需要对互斥量初始化

1)、如果是动态分配的互斥量,可以调用pthread_mutex_init()函数初始化

2)、如果是静态分配的互斥量,还可以把它置为常量PTHREAD_MUTEX_INITIALIZER

3)、动态分配的互斥量在释放内存之前需要调用pthread_mutex_destroy()

(1)、pthread_mutex_init互斥量的初始化函数

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr)

第一个参数:要初始化的互斥量

第二个参数:互斥量的属性(可以写NULL)

返回值:成功返回0,失败返回错误码

(2)、pthread_mutex_destory互斥量的销毁函数

int pthread_mutex_destory(pthread_mutex_t *mutex)

参数:要销毁的互斥量

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER(静态的方式);

(3)、pthread_mutex_lock加锁函数

 int pthread_mutex_lock(pthread_mutex_t *mutex)

参数:要加锁的互斥量

返回值:成功返回0,失败返回错误码

如果互斥量已经被锁住,那么会导致该线程阻塞。

(4)、pthread_mutex_trylock尝试加锁函数

 int pthread_mutex_trylock(pthread_mutex_t *mutex)

参数:要加锁的互斥量

返回值:成功返回0,失败返回错误码

如果互斥量已经被锁住,不会导致线程阻塞。

(5)、 pthread_mutex_unlock解锁函数

 int pthread_mutex_unlock(pthread_mutex_t *mutex)

参数:要解锁的互斥量

返回值:成功返回0,失败返回错误码

如果一个互斥量没有被锁住,那么解锁就会出错。

下面看一下代码:


 
 
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <signal.h>
  7. #include <errno.h>
  8. //创建一个结构体,数据类型都一样是为了方便赋值
  9. struct student
  10. {
  11. int id;
  12. int age;
  13. int name;
  14. }stu;
  15. //定义两个全局变量,因为两个线程都要使用
  16. int i;
  17. pthread_mutex_t mutex;
  18. void *thread_fun1(void *arg)
  19. {
  20. while( 1)
  21. {
  22. //加锁,对整个结构体访问进行加锁,防止产生错码
  23. pthread_mutex_lock(&mutex);
  24. stu.id = i;
  25. stu.age = i;
  26. stu.name = i;
  27. i++;
  28. if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
  29. {
  30. printf( "thread 1 %d,%d,%d\n", stu.id, stu.age, stu.name);
  31. break;
  32. }
  33. //访问变量完成,需要进行解锁,只有这样其他线程才能访问
  34. pthread_mutex_unlock(&mutex);
  35. }
  36. return ( void *) 0;
  37. }
  38. void *thread_fun2(void *arg)
  39. {
  40. while( 1)
  41. {
  42. pthread_mutex_lock(&mutex);
  43. stu.id = i;
  44. stu.age = i;
  45. stu.name = i;
  46. i++;
  47. if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
  48. {
  49. printf( "thread 2 %d,%d,%d\n", stu.id, stu.age, stu.name);
  50. break;
  51. }
  52. pthread_mutex_unlock(&mutex);
  53. }
  54. return ( void *) 0;
  55. }
  56. int main()
  57. {
  58. pthread_t tid1,tid2;
  59. int err;
  60. //对互斥量进行初始化,只有初始化过后互斥量才能使用
  61. err = pthread_mutex_init(&mutex, NULL);
  62. if(err != 0)
  63. {
  64. printf( "init mutex failure\n");
  65. return ;
  66. }
  67. //创建新的线程
  68. err = pthread_create(&tid1, NULL,thread_fun1, NULL);
  69. if(err != 0)
  70. {
  71. printf( "create new thread failure\n");
  72. return;
  73. }
  74. //创建新的线程
  75. err = pthread_create(&tid1, NULL,thread_fun1, NULL);
  76. if(err != 0)
  77. {
  78. printf( "create new thread failure\n");
  79. return;
  80. }
  81. //等待新线程运行结束
  82. pthread_join(tid1, NULL);
  83. pthread_join(tid2, NULL);
  84. return 0;
  85. }

注意:加锁函数和解锁函数要成对的出现否则会出现错误。

2、读写锁

读写锁与互斥量类似,不过读写锁有更高的并行性。互斥量要么加锁要么不加锁,而且同一时刻只允许一个线程对其加锁。对于一个变量的读取,完全可以让多个线程同时进行操作。

变量类型:pthread_rwlock_t  *rwlock

读写锁有三种状态,读模式下加锁,写模式下加锁,不加锁。一次只有一个线程可以占有写模式下的读写锁但是多个线程可以同时占有读模式的读写锁。读写锁在写加锁状态时,在它被解锁之前,所有试图对这个锁加锁的线程都会阻塞。读写锁在读加锁状态时,所有试图以读模式对其加锁的线程都会获得访问权,但是如果线程希望以写模式对其加锁,它必须阻塞直到所有的线程释放锁。

当读写锁以读模式加锁时,如果有线程试图以写模式对其加锁,那么读写锁会阻塞随后的读模式锁请求。这样可以避免读锁长期占用,而写锁达不到请求。(意思是如果现在处于读锁状态,有一个写锁发出请求,也有其他读锁发出请求,那么其他读锁会阻塞,写锁会执行)

读写锁非常适合对数据结构读次数大于写次数的程序,当它以读模式锁住时,是以共享的方式锁住的;当它以写模式锁住时,是以独占的模式锁住的。

(1)、pthread_rwlock_init读写锁初始化函数

 int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,  const pthread_rwlockattr_t *restrict attr)

第一个参数:要初始化的锁

第二个参数:锁属性(可写NULL)

返回值:成功返回0,失败返回错误码

(2)、pthread_rwlpck_destory读写锁销毁函数

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock)

参数:要销毁的锁

返回值:成功返回0,失败返回错误码

(3)、pthread_rwlock_rdlock读模式加锁

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(4)、pthread_rwlock_tryrdlock尝试读模式加锁函数

int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(5)、pthread_rwlock_wrlock写模式加锁

int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(6)、pthread_rwlock_trywrlock尝试写模式加锁

int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(7)、pthread_rwlock_unlock解锁函数

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)

参数:要解锁的锁

返回值:成功返回0,失败返回错误码

下面来看一下程序:


 
 
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <signal.h>
  7. #include <errno.h>
  8. //定义一个全局锁
  9. pthread_rwlock_t rwlock;
  10. int num= 0;
  11. void *thread_fun1(void *arg)
  12. {
  13. //读加锁
  14. // pthread_rwlock_rdlock(&rwlock);
  15. //写加锁
  16. pthread_rwlock_wrlock(&rwlock);
  17. printf( "the first thread print %d\n",num);
  18. sleep( 5);
  19. printf( "the first thread over\n");
  20. //解锁
  21. pthread_rwlock_unlock(&rwlock);
  22. return ( void *) 1;
  23. }
  24. void *thread_fun2(void *arg)
  25. {
  26. //读加锁
  27. // pthread_rwlock_rdlock(&rwlock);
  28. //写加锁
  29. pthread_rwlock_wrlock(&rwlock);
  30. printf( "the second thread print %d\n",num);
  31. sleep( 5);
  32. printf( "the second thread over\n");
  33. //解锁
  34. pthread_rwlock_unlock(&rwlock);
  35. return ( void *) 2;
  36. }
  37. int main()
  38. {
  39. pthread_t tid1,tid2;
  40. int err;
  41. //初始化读写锁
  42. err=pthread_rwlock_init(&rwlock, NULL);
  43. if(err != 0)
  44. {
  45. printf( "init rwlock failure\n");
  46. return;
  47. }
  48. //创建新的线程
  49. err=pthread_create(&tid1, NULL,thread_fun1, NULL);
  50. if(err != 0)
  51. {
  52. printf( "create new firest thread failure\n");
  53. return;
  54. }
  55. err=pthread_create(&tid2, NULL,thread_fun2, NULL);
  56. if(err != 0)
  57. {
  58. printf( "create new second thread failure\n");
  59. return;
  60. }
  61. //等待新线程执行完毕
  62. pthread_join(tid1, NULL);
  63. pthread_join(tid2, NULL);
  64. //读写锁的销毁
  65. pthread_rwlock_destroy(&rwlock);
  66. return 0;
  67. }

3、条件变量

一个典型的实例
在一条生产先线上有一个仓库,当生产者生产的时候需要锁住仓库独占,而消费者取产品的时候也要锁住仓库独占。如果生产者发现仓库满了,那么他就不能生产了,变成了阻塞状态。但是此时由于生产者独占仓库,消费者又无法进入仓库去消耗产品,这样就造成了一个僵死状态。

我们需要一种机制,当互斥量被锁住以后发现当前线程还是无法完成自己的操作,那么它应该释放互斥量,让其他线程工作。

1)、可以采用轮询的方式,不停的查询你需要的条件

2)、让系统来帮你查询条件,使用条件变量pthread_cond_t cond

(1)、pthread_cond_init条件变量初始化函数

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr)

第一个参数:要初始化的条件变量

第二个参数:条件变量属性(默认属性为NULL)

返回值:成功返回0,失败返回错误码

(2)、pthread_cond_destory条件变量销毁函数

int pthread_cond_destroy(pthread_cond_t *cond)

参数:要销毁的条件变量

返回值:成功返回0,失败返回错误码

(3)、 pthread_cond_wait等待条件变量被设置

 int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)

第一个参数:要设置的条件变量

第二个参数:互斥量

返回值:成功返回0,失败返回错误码

(4)、pthread_cond_timedwait等待条件变量被设置(指定等待时间)

int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime)

第一个参数:要设置的条件变量

第二个参数:互斥量

第三个参数:等待的时间

返回值:成功返回0,失败返回错误码

时间用下面的结构体表示:

 struct timespec{
                   time_t tv_sec;
                   long tv_nsec;
              };

这个函数与pthread_cond_wait类似,只是多一个timeout,如果到了指定的时间条件还不满足,那么就返回。注意,这个时间是绝对时间。例如你要等待3分钟,就要把当前时间加上3分钟然后转换到 timespec,而不是直接将3分钟转换到 timespec

用来等待条件变量被设置,值得注意的是等待调用需要一个已经上锁的互斥体mutex,这是为了防止在真正进入等待状态之前别的线程有可能设置该条件变量而产生竞争。

当条件满足的时候,需要唤醒等待条件的线程

1)、pthread_cond_broadcast用于设置条件变量,即使得事件发生,这样等待该事件的线程将不再阻塞

 int pthread_cond_broadcast(pthread_cond_t *cond)

参数:条件变量

2)、pthread_cond_signal则用于解除某一个等待线程的阻塞状态

int pthread_cond_signal(pthread_cond_t *cond)

参数:条件变量

注意,一定要在条件改变以后在唤醒线程

下面来看一下程序:

首先看一下程序框架图:

程序代码:


 
 
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <signal.h>
  7. #include <errno.h>
  8. #define BUFFER_SIZE 5 //产品库存大小
  9. #define PRODUCT_CNT 30 //产品生产总数
  10. struct product_cons
  11. {
  12. int buffer[BUFFER_SIZE]; //生产产品值
  13. pthread_mutex_t lock; //互斥锁
  14. int readpos,writepos; //读写位置
  15. pthread_cond_t notempty; //条件变量,非空
  16. pthread_cond_t notfull; //条件变量,非满
  17. }buffer;
  18. void init(struct product_cons *p)//初始化函数
  19. {
  20. pthread_mutex_init(&p->lock, NULL); //初始化互斥锁
  21. pthread_cond_init(&p->notempty, NULL); //初始化条件变量
  22. pthread_cond_init(&p->notfull, NULL); //初始化条件变量
  23. p->readpos = 0;
  24. p->writepos = 0;
  25. }
  26. void finish(struct product_cons *p)//销毁函数
  27. {
  28. pthread_mutex_destroy(&p->lock); //销毁互斥锁
  29. pthread_cond_destroy(&p->notempty); //销毁条件变量
  30. pthread_cond_destroy(&p->notfull); //销毁条件变量
  31. p->readpos = 0; //复位读指针复位
  32. p->writepos = 0; //复位写指针复位
  33. }
  34. //存储一个数据到buffer
  35. void put(struct product_cons *p,int data)//输入产品子函数
  36. {
  37. pthread_mutex_lock(&p->lock);
  38. if((p->writepos+ 1)%BUFFER_SIZE == p->readpos)
  39. {
  40. printf( "producer wait for not full\n");
  41. pthread_cond_wait(&p->notfull,&p->lock);
  42. }
  43. p->buffer[p->writepos] = data;
  44. p->writepos++;
  45. if(p->writepos >= BUFFER_SIZE)
  46. p->writepos = 0;
  47. pthread_cond_signal(&p->notempty);
  48. pthread_mutex_unlock(&p->lock);
  49. }
  50. //读,从buffer移除一个数据
  51. int get(struct product_cons *p)
  52. {
  53. int data;
  54. pthread_mutex_lock(&p->lock);
  55. if(p->readpos == p->writepos)
  56. {
  57. printf( "consumer wait for not empty\n");
  58. pthread_cond_wait(&p->notempty,&p->lock);
  59. }
  60. data=p->buffer[p->readpos];
  61. p->readpos++;
  62. if(p->readpos >=BUFFER_SIZE)
  63. p->readpos = 0;
  64. pthread_cond_signal(&p->notfull);
  65. pthread_mutex_unlock(&p->lock);
  66. return data;
  67. }
  68. void *producer(void *data)//子线程,生产
  69. {
  70. int n;
  71. for(n= 1;n< 30;n++)
  72. {
  73. sleep( 1);
  74. printf( "put the %d product.....\n",n);
  75. put(&buffer,n);
  76. printf( "put the %d protuct sucess\n",n);
  77. }
  78. printf( "producer stopped\n");
  79. return NULL;
  80. }
  81. void *consumer(void *data) //子线程,购买
  82. {
  83. static int cnt = 0;
  84. int num;
  85. while( 1)
  86. {
  87. sleep( 2);
  88. printf( "get product ...\n");
  89. num = get(&buffer);
  90. printf( "get the %d product success\n", num);
  91. if(++cnt == PRODUCT_CNT)
  92. break;
  93. }
  94. printf( "consumer stopped\n");
  95. return NULL;
  96. }
  97. int main(int argc, char *argv[])
  98. {
  99. pthread_t th_a,th_b;
  100. void *retval;
  101. //调用初始化函数
  102. init(&buffer);
  103. //创建新的线程
  104. pthread_create(&th_a, NULL, producer, 0);
  105. pthread_create(&th_b, NULL, consumer, 0);
  106. //链接新的线程
  107. pthread_join(th_a, &retval);
  108. pthread_join(th_b, &retval);
  109. //调用销毁函数
  110. finish(&buffer);
  111. return 0;
  112. }

 

阅读更多
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值