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

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

线程会创建了,如何在线程调用函数时,传入参数呢?则应如下所示:

  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5  
  7.   
  8. void* say_hello(void* args)  
  9. {  
  10.     int i = *((int*)args);//对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取;  
  11.     cout << "hello in " << i << endl;  
  12. }  
  13.   
  14. int main()  
  15. {  
  16.     pthread_t tids[NUM_THREADS];  
  17.     cout << "hello in main..." << endl;  
  18.     for(int i = 0; i < NUM_THREADS; ++i)  
  19.     {  
  20.         int ret = pthread_create(&tids[i], NULL, say_hello, (void *)&i);//传入的时候必须强制转换为void* 类型,即无类型指针  
  21.         cout << "Current pthread id =" << tids[i] << endl;//这里学会使用tids数组打印创建的进程id信息;  
  22.         if (ret != 0)  
  23.         {  
  24.            cout << "pthread_create error: error_code=" << ret << endl;  
  25.         }  
  26.     }  
  27.   
  28.     pthread_exit(NULL);  
  29. }  


编译、运行,结果如下:

  1. Current pthread id =139671233451792  
  2. Current pthread id =139671222961936  
  3. Current pthread id =139671212472080  
  4. Current pthread id =139671201982224  
  5. Current pthread id =139671191492368  
  6. hello in 4196496  
  7. hello in 4196496  
  8. hello in 4196496  
  9. hello in 4196496  
  10. hello in 4196496  

是否发现了问题?对,i的值没有输出预想的结果,这是因为多线程造成的,主进程在i还未赋值时,线程已经开始跑啦!~

那么下面代码是正确的:

  1. #include <iostream>  
  2. #include <pthread.h>  
  3.   
  4. using namespace std;  
  5.   
  6. #define NUM_THREADS 5  
  7.   
  8. void* say_hello(void* args)  
  9. {  
  10.     cout << "hello in thread " << *((int *)args) << endl;  
  11. }  
  12.   
  13. int main()  
  14. {  
  15.     pthread_t tids[NUM_THREADS];  
  16.     int indexes[NUM_THREADS];//用个数组来保存i的值,就不会变了  
  17.   
  18.     for(int i = 0; i < NUM_THREADS; ++i)  
  19.     {  
  20.         indexes[i] = i;//先保存i的值,在调用线程就不会出现问题了  
  21.         int ret = pthread_create( &tids[i], NULL, say_hello, (void *)&(indexes[i]) );  
  22.         if (ret != 0)  
  23.         {  
  24.            cout << "pthread_create error: error_code=" << ret << endl;  
  25.         }  
  26.     }  
  27.     for (int i = 0; i < NUM_THREADS; ++i)  
  28.         pthread_join(tids[i], NULL);  
  29. }  

编译、运行:(源程序去掉了打印线程id的废话)

    1. [cpp@node2 pthread]$ ./ex_create_args_ok  
    2. hello in thread 3  
    3. hello in thread 4  
    4. hello in thread 2  
    5. hello in thread 1  
    6. hello in thread 0 
posted @ 2012-09-04 12:14  董雨  阅读(835)  评论(0编辑  收藏  举报