羊咩 2017-03-29 05:39 采纳率: 100%
浏览 1032
已采纳

c++ 多线程, 一读一写, 为什么写线程 无法修改

#include
#include
#include

uint indx;
void wFunc();
void rFunc();

int main(){

    indx=0;

    std::thread *pwthd=new std::thread(wFunc);
    pwthd->detach();

    std::thread *prthd=new std::thread(rFunc);
    prthd->detach();

sleep(60);

}

void wFunc(){

    uint tmp=indx;

    while(true){
            tmp++;
            indx=tmp;
            std::cout<<"w indx:"<<tmp<<std::endl;
            sleep(1);
}

}

void rFunc(){

    uint tmp=indx;

    while(true){

            if(indx>tmp){
                tmp=indx;
                std::cout<<"r indx:"<<tmp<<std::endl;
            }

    }

}

  • 写回答

2条回答 默认 最新

  • oyljerry 2017-03-29 06:10
    关注

    加一个修饰

     volatile uint indx;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?