简体   繁体   English

使用不同版本编译的相同代码提供不同的结果

[英]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). 我正在使用一个我无法控制的外部库,也不知道内部(我们称之为privcallbacks)。

I know that I have a class called callbacks that has two bool variables: 我知道我有一个名为callbacks的类,它有两个bool变量:

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. 此代码在两个不同的Linux版本中正确编译,具有两个不同的GCC版本和LIBC版本。

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. 在最近的一个(linux mint,GCC 5.4 LIBC 2.23)中,我运行应用程序,在while中查看cout,当调用回调时,代码存在于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. 在旧的(debian,GCC 4.9.2,LIBC 2.19)中,while永远不存在,变量总是假的,即使我可以从回调内部看到打印。

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()方法可以明显看出,涉及多个执行线程。 test() is in one execution thread, and the callbacks get invoked by the other execution thread. test()在一个执行线程中,并且回调由另一个执行线程调用。

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. 在另一个执行线程中设置bool标志,并在test()执行线程中读取相同的标志不会相互排序。

The usual solution is to either use std::atomic_bool ; 通常的解决方案是使用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. 或者使用std::mutex来实现排序和访问变量,或者在一个执行线程中设置它们,或者只在互斥锁被锁定时在另一个执行线程中读取它们的当前值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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