简体   繁体   中英

Same code compiled with different versions provides different result

I am using an external library which I do not control nor know the internals (lets call it proprietarycallbacks).

I know that I have a class called callbacks that has two bool variables:

class callbacks : public proprietarycallbacks {
  bool a = false;
  bool b = false;
  virtual callbackHandler() {
    cout "callback received\n";
    b = true;
  }
}

then I have another class which inherits from the callbacks class:

class MyObject : public callbacks {

  void test() {
    while (!b) {
      cout << "test " << a << " " << b << endl;
      usleep(100000);
    }
  }
}

This code compiles correctly in two different linux versions, with two different GCC versions and LIBC versions.

On the most recent one (linux mint, GCC 5.4 LIBC 2.23), I run the app, see the cout in the while and when the callback is called, the code exists the while.

On the older one (debian, GCC 4.9.2, LIBC 2.19), the while never exists, the variable is always false, even though I can see the print from inside the callback.

Is there something wrong with the way I am structuring the code, and the variable inheritance, or does this have something to do with the software versions I am using?

Thank you for your time

It is obvious from your test() method that there are multiple execution threads involved. test() is in one execution thread, and the callbacks get invoked by the other execution thread.

Setting the bool flags in the other execution thread, and reading the same flags in the test() execution thread are not sequenced with each other.

The usual solution is to either use std::atomic_bool ; or use a std::mutex to implement sequencing, and accessing the variables, either to set them in one execution thread, or read their current values in the other execution thread, only while the mutex is locked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM