C ++似乎变量与多线程" flush "

c++ it seems that variable doesn't " flush " with multi thread

本文关键字:多线程 flush 变量      更新时间:2023-10-16

is_master_ def:

volatile bool is_master_;

is_master_值被另一个线程设置为 true,但似乎is_master_值 dosnt 刷新(它不会产生致命错误......如果我添加 cout <<"foo"<

void MasterSlaveSynchronize::validateSingleMaster(){
    if(is_master_){
        cout << "FATAL ERROR HAS OCCURRED BOTH MASTER";
        if(!is_leader_master_){
            cout << "CHOSE AS VICTIM IN MASTER-MATSER. SET THIS HOST AS SLAVE";
            is_master_ = false;
        }
    }
}
>

来电代码:

while(1){
        int n = recvfrom(sockId, buf, HEARBEAT_SIZE, 0, (struct sockaddr *) &from,
                &length);
        if (n < 0) {
            REGISTER_ERROR("Failed to recieved hearbeat");
        } else {
            gettimeofday(&instance_->last_hearbeat_got_, NULL);
            instance_->validateSingleMaster();
        }
}

您希望我发表评论作为答案:

也许确实如此,但是因为您不使用换行符,因此输出流 不冲洗。

这种行为在这里得到了很好的解释:

为什么 printf 在调用后不会刷新,除非格式字符串中有换行符?