码迷,mamicode.com
首页 > 编程语言 > 详细

线程的同步

时间:2015-06-26 19:37:48      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

多个线程共享相同的内存时,需要确保每个线程看到一致的数据视图。

1.互斥量

可以通过使用pthread的互斥接口保护数据,确保同一时间只有一个线程访问数据,互斥量(mutex)从本质上说是一把
锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥
量进行加锁的线程将被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上阻塞线程都会
变成可运行状态,第一个变为运行状态的线程可以对互斥量进行加锁,其他线程将会看到互斥锁依然被锁住,只有回去再次等
待它重新变成可用。在这种方式下,每次只有一个线程可以向前执行。
互斥变量用pthread_mutex_t数据类型来表示,在使用互斥变量以前,必须首先对它进行初始化,可以把它置为常量
PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地
分配互斥量(例如通过调用malloc),那么在释放内存前需要调用pthread_mutex_destroy。
[cpp] view plaincopy技术分享技术分享
 
  1. #include<pthread.h>  
  2. int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);  
  3. int pthread_mutex_destroy(pthread_mutex_t * mutex);  
  4. //成功返回0,否则返回错误编号  
使用默认的属性初始化互斥量,只要将attr设置为NULL。
 
对互斥量进行加锁,需要调用pthread_mutex_lock,如果互斥量已经上锁,调用线程将阻塞直到互斥量被解锁。对互斥量
解锁,需要调用pthread_mutex_unlock。
[cpp] view plaincopy技术分享技术分享
 
  1. #include <pthread.h>  
  2. int pthread_mutex_lock(pthread_mutex_t *mutex);  
  3. int pthread_mutex_trylock(pthread_mutex_t *mutex);  
  4. int pthread_mutex_unlock(pthread_mutex_t *mutex);  
  5. //如果成功返回0,否则返回错误编号。  
如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时
互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现并返回0,否则pthread_mutex_trylock就会失败,
不能锁住互斥量,而返回EBUSY
 
 
实践:
在没有使用互斥锁时:
[cpp] view plaincopy技术分享技术分享
 
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <malloc.h>  
  4. #include <string.h>  
  5.   
  6. void* th_func(void* arg){  
  7.         int i;  
  8.         for(i=0; i<5; i++){  
  9.                 printf("1\n");  
  10.                 sleep(1);  
  11.                 printf("2\n");  
  12.         }  
  13. }  
  14.   
  15. int main(void){  
  16.         int ret;  
  17.         pthread_t tid1,tid2;  
  18.   
  19.         ret = pthread_create(&tid1, NULL, th_func, NULL);  
  20.         if(ret != 0){  
  21.                 printf("pthread_create:%s\n",strerror(ret));  
  22.                 return -1;  
  23.         }  
  24.         ret = pthread_detach(tid1);  
  25.         if(ret != 0){  
  26.                 printf("pthread_detach:%s\n",strerror(ret));  
  27.                 return -1;  
  28.         }  
  29.   
  30.         ret = pthread_create(&tid2, NULL, th_func, NULL);  
  31.         if(ret != 0){  
  32.                 printf("pthread_create:%s\n",strerror(ret));  
  33.                 return -1;  
  34.         }  
  35.         ret = pthread_detach(tid2);  
  36.         if(ret != 0){  
  37.                 printf("pthread_detach:%s\n",strerror(ret));  
  38.                 return -1;  
  39.         }  
  40.   
  41.         sleep(15);  
  42.         return 0;  
  43. }  
程序输出为:
1
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
2
 
使用了互斥锁之后:
[cpp] view plaincopy技术分享技术分享
 
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <malloc.h>  
  4. #include <string.h>  
  5.   
  6. pthread_mutex_t *mutex;  
  7.   
  8. void* th_func(void* arg){  
  9.         int i;  
  10.         for(i=0; i<5; i++){  
  11.                 pthread_mutex_lock(mutex);  
  12.                 printf("1\n");  
  13.                 sleep(1);  
  14.                 printf("2\n");  
  15.                 pthread_mutex_unlock(mutex);  
  16.         }  
  17. }  
  18.   
  19. int main(void){  
  20.         int ret,result = 0;  
  21.         pthread_t tid1,tid2;  
  22.   
  23.         mutex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));  
  24.         if(mutex == NULL){  
  25.                 perror("malloc");  
  26.                 result = -1;  
  27.                 goto FINALLY;  
  28.         }  
  29.         pthread_mutex_init(mutex,NULL);  
  30.   
  31.         ret = pthread_create(&tid1, NULL, th_func, NULL);  
  32.         if(ret != 0){  
  33.                 printf("pthread_create:%s\n",strerror(ret));  
  34.                 result = -1;  
  35.                 goto FINALLY;  
  36.         }  
  37.         ret = pthread_detach(tid1);  
  38.         if(ret != 0){  
  39.                 printf("pthread_detach:%s\n",strerror(ret));  
  40.                 result = -1;  
  41.                 goto FINALLY;  
  42.         }  
  43.   
  44.         ret = pthread_create(&tid2, NULL, th_func, NULL);  
  45.         if(ret != 0){  
  46.                 printf("pthread_create:%s\n",strerror(ret));  
  47.                 result = -1;  
  48.                 goto FINALLY;  
  49.         }  
  50.         ret = pthread_detach(tid2);  
  51.         if(ret != 0){  
  52.                 printf("pthread_detach:%s\n",strerror(ret));  
  53.                 result = -1;  
  54.                 goto FINALLY;  
  55.         }  
  56.   
  57.         sleep(15);  
  58.   
  59. FINALLY:  
  60.   
  61.         if(mutex != NULL){  
  62.                 pthread_mutex_destroy(mutex);  
  63.                 free(mutex);  
  64.         }  
  65.         return result;  
  66. }  
程序输出为:
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2
 

2.避免死锁

如果线程试图对同一个互斥量加锁两次,那么它自身就会陷入死锁状态,使用互斥量时,还有其他更不明显的方式也能产生死锁,
例如,程序中使用多个互斥量,如果允许一个线程一直占有一个互斥量,并且试图锁住第二个互斥量时处于阻塞状态,但是拥有第二
个互斥量的线程也在试图锁住第一个互斥量,这时就会发生死锁。因为两个线程都在相互请求另一个线程拥有的资源,所以这两个线程
都无法向前运行,于是就产生死锁。
可以通过控制互斥量加锁的顺序来避免死锁的发生。例如,假设需要对两个互斥量A和B同时加锁,如果所有线程总是在对互斥量B
加锁之前锁住A,那么使用这两个互斥量不会产生死锁,类似地,如果所有的线程总是在锁住互斥量A之前锁住B,那么也不会发生死
锁。 //顺序加锁法
 

3.读写锁

读写锁与互斥量类似,不过读写锁允许更高的并行性。互斥量要么是锁住状态要么不加锁状态,而且一次只有一个线程可以对其
加锁。读写锁可以有三种状态:读模式下加锁状态,写模式下加锁状态,不加锁状态。一次只有一个线程可以占有写模式的读写锁,
但是多个线程可以同时占有读模式的读写锁。
当读写锁是写加锁状态时,在这个锁被解锁之前,所有试图对这个锁加锁的线程都会被阻塞。当读写锁在读加锁状态时,所有试图
以读模式对它进行加锁的线程都可以得到访问权,但是如果线程希望以写模式对此锁进行加锁,他必须阻塞直到所有的线程释放读锁
当读写锁处理读模式锁住状态时,如果有另外的线程试图以写模式加锁,读写锁通常会阻塞随后的读模式锁请求,这样可以避免读模式
锁长期占用,而等待的写模式请求一直得不到满足。
读写锁非常适用于对数据结构读的次数远大于写的情况
通过调用pthread_rwlock_init进程初始化,如果希望读写锁有默认的属性,可以传一个空指针给attr。
在释放读写锁占用的内存之前,需要调用pthread_rwlock_destroy做清理工作
[cpp] view plaincopy技术分享技术分享
 
  1. #include <pthread.h>  
  2. int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);  
  3. int pthread_rwlock_destory(pthread_rwlock_t *rwlock);  
  4. //若成功返回0,否则返回错误编号。  
 
在读模式下锁住读写锁,需要调用pthread_rwlock_rdlock,要在写模式下锁定读写锁,需要调用pthread_rwlock_wrlock,不管以
何种方式锁住读写锁,都可以调用pthread_rwlock_unlock进行解锁。
[cpp] view plaincopy技术分享技术分享
 
  1. #include<pthread.h>  
  2. int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);  
  3. int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);  
  4. int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);  
  5. //成功则返回0,否则返回错误编号。  
 
Single UNIX Specification同样定义了有条件的读写锁原语版本。
[cpp] view plaincopy技术分享技术分享
 
  1. #include <pthread.h>  
  2. int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);  
  3. int pthread_rwlock_tryrwlock(pthread_rwlock_t *rwlock);  
  4. //成功返回0,否则返回错误编号。  
 
实践:
[cpp] view plaincopy技术分享技术分享
 
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <malloc.h>  
  4. #include <string.h>  
  5.   
  6. pthread_rwlock_t *rwlock;  
  7.   
  8. int gi=0;  
  9.   
  10. void* th_func1(void* arg){  
  11.         int i;  
  12.         for(i=0; i<5; i++){  
  13.                 pthread_rwlock_rdlock(rwlock);  
  14.                 printf("start1:%d\n",gi);  
  15.                 sleep(1);  
  16.                 printf("end1:%d\n",gi);  
  17.                 pthread_rwlock_unlock(rwlock);  
  18.                 sleep(1);  
  19.         }  
  20. }  
  21.   
  22. void* th_func2(void* arg){  
  23.         int i;  
  24.         for(i=0; i<5; i++){  
  25.                 pthread_rwlock_rdlock(rwlock);  
  26.                 printf("start2:%d\n",gi);  
  27.                 sleep(1);  
  28.                 printf("end2:%d\n",gi);  
  29.                 pthread_rwlock_unlock(rwlock);  
  30.                 sleep(1);  
  31.         }  
  32. }  
  33.   
  34. void* th_func3(void* arg){  
  35.         int i;  
  36.         for(i=0; i<5; i++){  
  37.                 pthread_rwlock_wrlock(rwlock);  
  38.                 gi++;  
  39.                 sleep(1);  
  40.                 pthread_rwlock_unlock(rwlock);  
  41.                 sleep(1);  
  42.         }  
  43. }  
  44.   
  45. int main(void){  
  46.         int ret,result = 0;  
  47.         pthread_t tid1,tid2,tid3;  
  48.   
  49.         rwlock = (pthread_rwlock_t*)malloc(sizeof(pthread_rwlock_t));  
  50.         if(rwlock == NULL){  
  51.                 perror("malloc");  
  52.                 goto FINALLY;  
  53.         }  
  54.   
  55.         ret = pthread_create(&tid1, NULL, th_func1, NULL);  
  56.         if(ret != 0){  
  57.                 printf("pthread_create:%s\n",strerror(ret));  
  58.                 result = -1;  
  59.                 goto FINALLY;  
  60.         }  
  61.         ret = pthread_detach(tid1);  
  62.         if(ret != 0){  
  63.                 printf("pthread_detach:%s\n",strerror(ret));  
  64.                 result = -1;  
  65.                 goto FINALLY;  
  66.         }  
  67.   
  68.         ret = pthread_create(&tid2, NULL, th_func2, NULL);  
  69.         if(ret != 0){  
  70.                 printf("pthread_create:%s\n",strerror(ret));  
  71.                 result = -1;  
  72.                 goto FINALLY;  
  73.         }  
  74.         ret = pthread_detach(tid2);  
  75.         if(ret != 0){  
  76.                 printf("pthread_detach:%s\n",strerror(ret));  
  77.                 result = -1;  
  78.                 goto FINALLY;  
  79.         }  
  80.   
  81.         ret = pthread_create(&tid3, NULL, th_func3, NULL);  
  82.         if(ret != 0){  
  83.                 printf("pthread_create:%s\n",strerror(ret));  
  84.                 result = -1;  
  85.                 goto FINALLY;  
  86.         }  
  87.         ret = pthread_detach(tid3);  
  88.         if(ret != 0){  
  89.                 printf("pthread_detach:%s\n",strerror(ret));  
  90.                 result = -1;  
  91.                 goto FINALLY;  
  92.         }  
  93.   
  94.         sleep(15);  
  95.   
  96. FINALLY:  
  97.         if(rwlock != NULL){  
  98.                 pthread_rwlock_destroy(rwlock);  
  99.                 free(rwlock);  
  100.         }  
  101.         return result;  
  102. }  
结果:
start2:1
start1:1
end2:1
end1:1
start2:2
start1:2
end2:2
end1:2
start2:3
start1:3
end2:3
end1:3
start2:4
start1:4
end2:4
end1:4
start2:5
start1:5
end2:5
end1:5
一次循环中start和end中的值都是一样的。
 
如果我们修改下程序:
[cpp] view plaincopy技术分享技术分享
 
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <malloc.h>  
  4. #include <string.h>  
  5.   
  6. int gi=0;  
  7.   
  8. void* th_func1(void* arg){  
  9.         int i;  
  10.         for(i=0; i<5; i++){  
  11.                 printf("start1:%d\n",gi);  
  12.                 sleep(1);  
  13.                 printf("end1:%d\n",gi);  
  14.                 sleep(1);  
  15.         }  
  16. }  
  17.   
  18. void* th_func2(void* arg){  
  19.         int i;  
  20.         for(i=0; i<5; i++){  
  21.                 printf("start2:%d\n",gi);  
  22.                 sleep(1);  
  23.                 printf("end2:%d\n",gi);  
  24.                 sleep(1);  
  25.         }  
  26. }  
  27.   
  28. void* th_func3(void* arg){  
  29.         int i;  
  30.         for(i=0; i<5; i++){  
  31.                 gi++;  
  32.                 sleep(1);  
  33.         }  
  34. }  
  35.   
  36. int main(void){  
  37.         int ret,result = 0;  
  38.         pthread_t tid1,tid2,tid3;  
  39.   
  40.         ret = pthread_create(&tid1, NULL, th_func1, NULL);  
  41.         if(ret != 0){  
  42.                 printf("pthread_create:%s\n",strerror(ret));  
  43.                 result = -1;  
  44.                 goto FINALLY;  
  45.         }  
  46.         ret = pthread_detach(tid1);  
  47.         if(ret != 0){  
  48.                 printf("pthread_detach:%s\n",strerror(ret));  
  49.                 result = -1;  
  50.                 goto FINALLY;  
  51.         }  
  52.   
  53.         ret = pthread_create(&tid2, NULL, th_func2, NULL);  
  54.         if(ret != 0){  
  55.                 printf("pthread_create:%s\n",strerror(ret));  
  56.                 result = -1;  
  57.                 goto FINALLY;  
  58.         }  
  59.         ret = pthread_detach(tid2);  
  60.         if(ret != 0){  
  61.                 printf("pthread_detach:%s\n",strerror(ret));  
  62.                 result = -1;  
  63.                 goto FINALLY;  
  64.         }  
  65.   
  66.         ret = pthread_create(&tid3, NULL, th_func3, NULL);  
  67.         if(ret != 0){  
  68.                 printf("pthread_create:%s\n",strerror(ret));  
  69.                 result = -1;  
  70.                 goto FINALLY;  
  71.         }  
  72.         ret = pthread_detach(tid3);  
  73.         if(ret != 0){  
  74.                 printf("pthread_detach:%s\n",strerror(ret));  
  75.                 result = -1;  
  76.                 goto FINALLY;  
  77.         }  
  78.   
  79.         sleep(15);  
  80.   
  81. FINALLY:  
  82.         return result;  
  83. }  
运行结果:
start2:1
start1:1
end2:2
end1:2
start2:3
start1:3
end2:4
end1:4
start2:5
start1:5
end2:5
end1:5
start2:5
start1:5
end2:5
end1:5
start2:5
start1:5
end2:5
end1:5
一次循环中start和end中的值可能会不一样。
 

4.条件变量

条件变量是线程可用的另一种同步机制。条件变量给多个线程提供了一个回合的场所。条件变量与互斥量一起使用时,允许线程
以无竞争的方式等待特定的条件发生。
条件本身是由互斥量保护的,线程在改变条件状态前必须首先锁住互斥量,其他线程在获得互斥量之前不会觉察到这种改变,因为
必须锁住互斥量后才能计算条件。
条件变量使用之前必须先进行初始化,pthread_cond_t数据结构代表的条件变量可以用两种方式进行初始化,可以把常量
PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用pthread_cond_init函数初始化。
在释放底层的内存空间之前,可以使用pthread_cond_destroy函数对条件变量进行去除初始化。
[cpp] view plaincopy技术分享技术分享
 
  1. #include<pthread.h>  
  2. int pthread_cond_init(pthread_cond_t *restrict cond, pthread_condattr_t *restrict attr);  
  3. int pthread_cond_destroy(pthread_cond_t *cond);  
  4. //成功则返回0,否则返回错误编号。  
使用pthread_cond_wait等待条件变成真
[cpp] view plaincopy技术分享技术分享
 
  1. #include<pthread.h>  
  2. int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);  
  3. //成功返回0,否则返回错误编号。  
传递给pthread_cond_wait的互斥量对条件进行保护,调用者把锁住的互斥量传给函数。函数把调用线程放到等待条件的线程列表上,
然后对互斥量解锁,这两个操作是原子操作,这样就关闭了条件检查和线程进入休眠状态等待条件改变这两个操作之间的时间通道,
这样线程就不会错过条件的任何变化,pthread_cond_wait返回时,互斥量再次被锁住。
 
[cpp] view plaincopy技术分享技术分享
 
  1. #include<pthread.h>  
  2. int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex,  
  3. const struct timespec *restrict timeout);  
  4. //成功返回0,否则返回错误编号。  
pthread_cond_timedwait函数的工作方式与pthread_cond_wait函数相似,只是多了一个timeout,timeout值指定了等待的时间。它
通过timespec结构指定。
[cpp] view plaincopy技术分享技术分享
 
  1. struct timespec{  
  2.     time_t tv_sec; //秒数  
  3.     long tv_nsec; //纳秒  
  4. }  
使用这个结构体时,需要指定等待多长时间,时间值是一个绝对值而不是相对值,例如如果要等待3分钟,就需要把当前时间加上3分钟
再转换到timespec结构。
如果时间到了但是条件还是没有出现,pthread_cond_timedwait将重新获取互斥量然后返回错误ETIMEDOUT。
从pthread_cond_wait或者pthread_cond_timedwait调用成功返回时,线程需要重新计算条件,因为其他的线程可能已经在运行并改变
了条件。
 
有两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该线程的某个线程,而pthread_cond_broadcast函数
将唤醒等待该条件的所有线程。
[cpp] view plaincopy技术分享技术分享
 
  1. #include <pthread.h>  
  2. int pthread_cond_siganl(pthread_cond_t *cond);  
  3. int pthread_cond_broadcast(pthread_cond_t *cond);  
  4. //成功则返回0,否则返回错误编号。  
实践:
[cpp] view plaincopy技术分享技术分享
 
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <string.h>  
  4.   
  5. pthread_cond_t qready = PTHREAD_COND_INITIALIZER;  
  6. pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;  
  7.   
  8. int gi=0;  
  9.   
  10. void* substract(void* arg){  
  11.         int i;  
  12.         for(i=0; i<5; i++){  
  13.                 pthread_mutex_lock(&qlock);  
  14.                 while(gi == 0)  
  15.                         pthread_cond_wait(&qready, &qlock);  
  16.                 printf("before substract gi:%d.\n",gi);  
  17.                 gi--;  
  18.                 printf("after substract gi:%d.\n",gi);  
  19.                 pthread_mutex_unlock(&qlock);  
  20.         }  
  21. }  
  22.   
  23. void* add(void* arg){  
  24.         int i;  
  25.         for(i=0; i<5; i++){  
  26.                 pthread_mutex_lock(&qlock);  
  27.                 printf("before add gi:%d.\n",gi);  
  28.                 gi++;  
  29.                 printf("after add gi:%d.\n",gi);  
  30.                 pthread_mutex_unlock(&qlock);  
  31.                 pthread_cond_signal(&qready);  
  32.         }  
  33. }  
  34.   
  35. int main(void){  
  36.         int ret;  
  37.         pthread_t tid1,tid2;  
  38.   
  39.         ret = pthread_create(&tid1, NULL, substract, NULL);  
  40.         if(ret != 0){  
  41.                 printf("pthread_create:%s",strerror(ret));  
  42.                 return -1;  
  43.         }  
  44. <span style="white-space:pre">  </span>sleep(1);   
  45.         ret = pthread_create(&tid2, NULL, add, NULL);  
  46.         if(ret != 0){  
  47.                 printf("pthread_create:%s",strerror(ret));  
  48.                 return -1;  
  49.         }  
  50.   
  51.         ret = pthread_join(tid1,NULL);  
  52.         if(ret != 0){  
  53.                 printf("pthread_join:%s",strerror(ret));  
  54.                 return -1;  
  55.         }  
  56.   
  57.         ret = pthread_join(tid2,NULL);  
  58.         if(ret != 0){  
  59.                 printf("pthread_join:%s",strerror(ret));  
  60.                 return -1;  
  61.         }  
  62.   
  63.         return 0;  
  64. }  
运行结果:
before add gi:0.
after add gi:1.
before substract gi:1.
after substract gi:0.
before add gi:0.
after add gi:1.
before substract gi:1.
after substract gi:0.
before add gi:0.
after add gi:1.
before substract gi:1.
after substract gi:0.
before add gi:0.
after add gi:1.
before substract gi:1.
after substract gi:0.
before add gi:0.
after add gi:1.
before substract gi:1.
after substract gi:0.

线程的同步

标签:

原文地址:http://www.cnblogs.com/QingCHOW/p/4603063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!