关于c++多线程全局变量访问

关于c++多线程全局变量访问

在多线程代码的测试过程中,可能会出现全局变量的访问冲突问题,可以通过引入锁(互斥锁、读写锁),获得锁定线程完成“读——修改——写”的操作后,释放锁给其他线程,没有获得锁的线程只能等待而不能访问,这样“读——修改——写”3步操作不会执行到中间被其他线程打断,可以完整的执行下去。

测试代码

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <string.h>
#include <cstdlib>
#define thread_lock_test 1

phread_mutex_t lock;

int gcn = 0;   //定义一个全局变量,用于累加
 
void *thread_1(void *arg) {    //第一个线程
#if thread_lock_test
	pthread_mutex_lock(&lock);	//锁定
#endif
    int j;
    for (j = 0; j < 1000000; j++) {  //开始累加
        gcn++;
    }  
#if thread_lock_test
	pthread_mutex_unlock(&lock);	//解锁
#endif
    pthread_exit((void *)0);
}
 
void *thread_2(void *arg) {   //第二个线程
#if thread_lock_test
	pthread_mutex_lock(&lock);
#endif
    int j;
    for (j = 0; j < 1000000; j++) {   //开始累加     
        gcn++;
    }  
#if thread_lock_test
	pthread_mutex_unlock(&lock);
#endif
    pthread_exit((void *)0);
}
int main(void)
{
#if thread_lock_test
	pthread_mutex_init(&lock, NULL);
#endif
    int j,err;
    pthread_t th1, th2;
     
    for (j = 0; j < 10; j++)   //做10次测试
    {
        err = pthread_create(&th1, NULL, thread_1, (void *)0);   //创建第1个线程
        if (err != 0) {
            printf("create new thread error:%s\n", strerror(err));
            exit(0);
        }  
        err = pthread_create(&th2, NULL, thread_2, (void *)0);   //创建第2个线程
        if (err != 0) {
            printf("create new thread error:%s\n", strerror(err));
            exit(0);
        }  
           
        err = pthread_join(th1, NULL);   //等待第一个线程结束
        if (err != 0) {
            printf("wait thread done error:%s\n", strerror(err));
            exit(1);
        }
        err = pthread_join(th2, NULL);   //等待第二个线程结束
        if (err != 0) {
            printf("wait thread done error:%s\n", strerror(err));
            exit(1);
        }
        printf("gcn=%d\n", gcn);
        gcn = 0;
    }
    return 0;
}

测试结果

取消锁定后,则上述代码可能无法完成所有的累加。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值