首页 > 编程语言 > 详细

两线程竞争修改全局变量

时间:2016-04-16 11:02:37      阅读:198      评论:0      收藏:0      [点我收藏+]
#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);
}
  1. 定义两个线程, threads[0] 和 threads[1];

  2. 定义全局变量 int global = 0;

  3. 在函数assign_value中,更改全局变量global;

  4. 加mutex锁避免逻辑错误。

输出结果:

initial value 0
start with1
end with 1
start with2
end with 2
final value 2

本文出自 “胡一刀” 博客,谢绝转载!

两线程竞争修改全局变量

原文:http://11190017.blog.51cto.com/11180017/1764346

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!