http://blog.csdn.net/lzx_bupt/article/details/6910632
線程會建立了,如何線上程調用函數時,傳入參數呢?則應如下所示:
[cpp] view plaincopy
- #include <iostream>
- #include <pthread.h>
-
- using namespace std;
-
- #define NUM_THREADS 5
-
- void* say_hello(void* args)
- {
- int i = *((int*)args);//對傳入的參數進行強制類型轉換,由無類型指標變為整形數指標,然後再讀取;
- cout << "hello in " << i << endl;
- }
-
- int main()
- {
- pthread_t tids[NUM_THREADS];
- cout << "hello in main..." << endl;
- for(int i = 0; i < NUM_THREADS; ++i)
- {
- int ret = pthread_create(&tids[i], NULL, say_hello, (void *)&i);//傳入的時候必須強制轉換為void* 類型,即無類型指標
- cout << "Current pthread id =" << tids[i] << endl;//這裡學會使用tids數組列印建立的進程id資訊;
- if (ret != 0)
- {
- cout << "pthread_create error: error_code=" << ret << endl;
- }
- }
-
- pthread_exit(NULL);
- }
編譯、運行,結果如下:
[plain] view plaincopy
- Current pthread id =139671233451792
- Current pthread id =139671222961936
- Current pthread id =139671212472080
- Current pthread id =139671201982224
- Current pthread id =139671191492368
- hello in 4196496
- hello in 4196496
- hello in 4196496
- hello in 4196496
- hello in 4196496
是否發現了問題?對,i的值沒有輸出預想的結果,這是因為多線程造成的,主進程在i還未賦值時,線程已經開始跑啦!~
那麼下面代碼是正確的:
[cpp] view plaincopy
- #include <iostream>
- #include <pthread.h>
-
- using namespace std;
-
- #define NUM_THREADS 5
-
- void* say_hello(void* args)
- {
- cout << "hello in thread " << *((int *)args) << endl;
- }
-
- int main()
- {
- pthread_t tids[NUM_THREADS];
- int indexes[NUM_THREADS];//用個數組來儲存i的值,就不會變了
-
- for(int i = 0; i < NUM_THREADS; ++i)
- {
- indexes[i] = i;//先儲存i的值,在調用線程就不會出現問題了
- int ret = pthread_create( &tids[i], NULL, say_hello, (void *)&(indexes[i]) );
- if (ret != 0)
- {
- cout << "pthread_create error: error_code=" << ret << endl;
- }
- }
- for (int i = 0; i < NUM_THREADS; ++i)
- pthread_join(tids[i], NULL);
- }
編譯、運行:(來源程式去掉了列印線程id的廢話)
[plain] view plaincopy
- [cpp@node2 pthread]$ ./ex_create_args_ok
- hello in thread 3
- hello in thread 4
- hello in thread 2
- hello in thread 1
- hello in thread 0