0

is_master_ def:

volatile bool is_master_;

is_master_ value is set to true by another thread , but It seems that is_master_ value dosnt flush (it doesn't cout the FATAL ERROR HAS OCCURRED... ). If i add 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;
        }
    }
}

The caller code:

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();
        }
}
Panup Pong
  • 1,693
  • 1
  • 17
  • 38
Avihai Marchiano
  • 3,641
  • 3
  • 25
  • 50
  • 2
    Maybe it does, but because you don't use a newline your output stream doesn't flush. – paddy Oct 07 '12 at 10:42
  • What's the relationship between `is_master_` and `is_leader_master_`? – Marcelo Cantos Oct 07 '12 at 10:43
  • @MarceloCantos there are 2 different booleans. – Avihai Marchiano Oct 07 '12 at 10:44
  • @paddy you are right!!!!! Thanks, can you write it as an answer in order to mark it? can you please explain? Thank you!!! – Avihai Marchiano Oct 07 '12 at 10:50
  • I would advise you to read a bit more on `volatile` values and threads, while you are working on this. You would probably be better off using *atomics* than just volatiles here. – Matthieu M. Oct 07 '12 at 12:04
  • @MatthieuM. Tahnk you for your comment ? Do i need to use atmoics even for boolean (1 byte ) ? Why did you say better of , is there any conflict between them ? Shouldnt i use both in order to be on the safe side? Thank you – Avihai Marchiano Oct 07 '12 at 14:19
  • @user1495181: well, I am not *that* knowledgeable about threads and memory models, however I do know that depending on use `volatile` in C++ (unlike Java) is not sufficient to guarantee much. The problem is not necessarily the size, when coming to atomicity, it's the optimizations a compiler and/or CPU can do in reordering the memory reads and writes operations (or eliding them). `std::atomic` are built specifically to match the CPU primitives, so that you will get what you want. – Matthieu M. Oct 07 '12 at 14:26

1 Answers1

3

You wanted me to post my comment as an answer:

Maybe it does, but because you don't use a newline your output stream doesn't flush.

This behaviour is explained reasonably well here:

Why does printf not flush after the call unless a newline is in the format string?

Community
  • 1
  • 1
paddy
  • 52,396
  • 6
  • 51
  • 93