您的位置:首页 > 其它

两线程竞争修改全局变量

2016-04-16 06:46 417 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pthread mutex