#include <pthread.h> #include <iostream> using namespace std; int global = 0; #define NUMTHREADS 2 pthread_mutex_t mutexnum; struct thread_data{ int idx; }; struct thread_data thread_data_array[NUMTHREADS]; void * assign_value(void *param){ struct thread_data *my_data = (struct thread_data *) param; pthread_mutex_lock(&mutexnum); global = my_data->idx; cout << "start with" << global << endl; for(int i = 0; i < 1000; i++){} // do some work cout << "end with " << global << endl; pthread_mutex_unlock(&mutexnum); } int main(){ pthread_t threads[NUMTHREADS]; cout << "initial value " << global << endl; pthread_mutex_init(&mutexnum, NULL); for(int i = 0; i < NUMTHREADS; i++){ thread_data_array[i].idx = i + 1; pthread_create(&threads[i], NULL, assign_value, (void *) &thread_data_array[i]); } for(int i = 0; i < NUMTHREADS; i++) pthread_join(threads[i], NULL); cout << "final value " << global << endl; pthread_mutex_destroy(&mutexnum); pthread_exit(NULL); }
定義兩個線程, threads[0] 和 threads[1];
定義全局變量 int global = 0;
在函數assign_value中,更改全局變量global;
加mutex鎖避免邏輯錯誤。
輸出結果:
initial value 0
start with1
end with 1
start with2
end with 2
final value 2