c/c++: 多线程编程基础讲解(五)

http://blog.csdn.net/lzx_bupt/article/details/6913151

最近喜欢听大学听到的老歌,deutschland 德国世界杯时候流行的,据说不是主题曲但是比主题曲还要火。

本篇进入难点了,mutex互斥锁概念,mutex=mutual exclusion的缩写,顺便说一句:以前老师都爱用缩写,也不跟同学说全称,这尼玛能理解深刻么!下文是用法:

  1. #include <iostream>  
  2. #include <pthread.h>//按规矩不能少  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5  
  7.   
  8. int sum = 0;//定义个全局变量,让所有线程进行访问,这样就会出现同时写的情况,势必会需要锁机制;  
  9. pthread_mutex_t sum_mutex;  
  10.   
  11. void* say_hello(void* args)  
  12. {  
  13.     cout << "hello in thread " << *((int *)args) << endl;  
  14.     pthread_mutex_lock (&sum_mutex);//修改sum就先加锁,锁被占用就阻塞,直到拿到锁再修改sum;  
  15.     cout << "before sum is " << sum << " in thread " << *((int *)args) << endl;  
  16.     sum += *((int *)args);  
  17.     cout << "after sum is " << sum << " in thread " << *((int *)args) << endl;  
  18.     pthread_mutex_unlock (&sum_mutex);//完事后解锁,释放给其他线程使用;  
  19.   
  20.     pthread_exit(0);//退出随便扔个状态码  
  21. }  
  22.   
  23. int main()  
  24. {  
  25.     pthread_t tids[NUM_THREADS];  
  26.     int indexes[NUM_THREADS];  
  27.     //下三句是设置线程参数没啥可说的  
  28.     pthread_attr_t attr;  
  29.     pthread_attr_init(&attr);  
  30.     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);  
  31.   
  32.     pthread_mutex_init (&sum_mutex, NULL);//这句是对锁进行初始化,必须的;  
  33.   
  34.     for(int i = 0; i < NUM_THREADS; ++i)  
  35.     {  
  36.         indexes[i] = i;  
  37.         int ret = pthread_create( &tids[i], &attr, say_hello, (void *)&(indexes[i]) );//5个进程去你们去修改sum吧哈哈;  
  38.         if (ret != 0)  
  39.         {  
  40.            cout << "pthread_create error: error_code=" << ret << endl;  
  41.         }  
  42.     }  
  43.   
  44.     pthread_attr_destroy(&attr);//删除参数变量  
  45.   
  46.     void *status;  
  47.         for (int i = 0; i < NUM_THREADS; ++i)  
  48.     {  
  49.                 int ret = pthread_join(tids[i], &status);  
  50.         if (ret != 0)  
  51.         {  
  52.             cout << "pthread_join error: error_code=" << ret << endl;  
  53.         }  
  54.     }  
  55.   
  56.     cout << "finally sum is " << sum << endl;  
  57.   
  58.     pthread_mutex_destroy(&sum_mutex);//注销锁,可以看出使用pthread内置变量神马的都对应了销毁函数,估计是内存泄露相关的吧;  
  59. }  

惯例:g++ -lpthread -o ex_mutex ex_mutex.cpp

运行:

  1. hello in thread 4  
  2. before sum is 0 in thread 4  
  3. after sum is 4 in thread 4  
  4. hello in thread 3  
  5. before sum is 4 in thread 3  
  6. after sum is 7 in thread 3  
  7. hello in thread 2  
  8. before sum is 7 in thread 2  
  9. after sum is 9 in thread 2  
  10. hello in thread 1  
  11. before sum is 9 in thread 1  
  12. after sum is 10 in thread 1  
  13. hello in thread 0  
  14. before sum is 10 in thread 0  
  15. after sum is 10 in thread 0  
  16. finally sum is 10  

发现个现象,thread4先运行,很诡异吧而i是从0递增的,所以呢多线程的顺序是混乱的,混乱就是正常;只要sum访问及修改是正常的,就达到多线程的目的了,运行顺序不能作为参照;

posted @ 2012-09-04 12:16  董雨  阅读(292)  评论(0编辑  收藏  举报