#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
时间: 2025-01-07 13:23:18