温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

多线程的坑--volatile

发布时间:2020-07-17 08:41:40 来源:网络 阅读:387 作者:zy20140925 栏目:编程语言

多线程编程中 开优化选项时要谨慎否则容易掉坑里
先看下面的代码,开起两个线程,第二个线程把第一个线程的循环条件置成false 按逻辑来说这个应该能顺利结束的不过如果用
g++ -O3 -o multiThread multiThread.cpp -lpthread
编译的话TestThread1是退不出来的,只有 g_brun 加上 volatile关键字才能正常退出
因为在-O3优化选项下 执行TestThread1时g_brun会先读到寄存器中,编译器发现这个函数中g_brun没有任何改变所以不会再去内存中取值直接用寄存器中的备份,在TestThread2中改变了g_brun在内存中的值,对TestThread1中g_brun的寄存器备份没有任何影响。
加上volatile表示对该变量不优化每次都去内存中取值。

#include <pthread.h>
#include <iostream>
#include <unistd.h>
using namespace std;

//volatile bool g_brun = true;
bool g_brun = true;

void* TestThread1(void* arg)
{
    cout << "TestThread1 进入" << endl;

    long long ll = 0;
    while(g_brun)
        ll ++; 

    cout << "TestThread1 退出   ll:" << ll << endl;
}

void* TestThread2(void* arg)
{
    cout << "TestThread2 进入" << endl;
    g_brun = false;
    cout << "TestThread2 退出  设置 g_brun = false" << endl;
}

int main()
{
    pthread_t threadId1;
    pthread_create(&threadId1, NULL, TestThread1, NULL);
    usleep(1000000); // 保证TestThread1先执行
    pthread_t threadId2;
    pthread_create(&threadId2, NULL, TestThread2, NULL);

    pthread_join(threadId1,NULL);
    pthread_join(threadId2,NULL);

    return 0;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI