【问题标题】:a pointer to a shared object is different in different objects which owns it指向共享对象的指针在拥有它的不同对象中是不同的
【发布时间】:2015-06-06 17:45:55
【问题描述】:

我在共享指向共享对象的指针时遇到问题。我在A 类中有一个C 类型的对象,它与B 类型的对象共享指向它的指针。然后对象有一个线程正在更改对象c 的值val,但更改不会应用于存储在对象b 中的指针。任何人都可以帮助我为什么会发生这种情况?

BOOST:

#include <iostream>
#include <boost/thread.hpp>

class C {
public:
  C(int _val): val(_val) {

  }

  ~C(){

  }

  void live(){
    while (true){
      val = rand() % 1000;
      std::cout << "val = " << val << std::endl;
    }
  }

  void setVal(int a){

    val = a;
  }

  int getVal(){
    return val;
  }

private:
  int val;
};

class B {
public:
  B(C* _pointer){
    pointer = _pointer;
  }

  void live(){
    while (true);
  }

  ~B(){

  }

  C* pointer;
};

class A {
public:
  A(): c(10), b(&c) {

  }

  void init() {
    t0 = boost::thread(boost::bind(&B::live, b));
    t1 = boost::thread(boost::bind(&C::live, c));
  }

  ~A() {

  }

  boost::thread t0, t1;

  B b;
  C c;
};

void main() {
  A a;
  a.init();

  while (true){
    std::cout << a.b.pointer->getVal() << std::endl;
  }
}

C++ 11:

#include <iostream>
#include <thread>

class C {
public:
  C(int _val): val(_val) {

  }

  ~C(){

  }

  void live(){
    while (true){
      val = rand() % 1000;
      std::cout << "val = " << val << std::endl;
    }
  }

  void setVal(int a){

    val = a;
  }

  int getVal(){
    return val;
  }

private:
  int val;
};

class B {
public:
  B(C* _pointer){
    pointer = _pointer;
  }

  void live(){
    while (true);
  }

  ~B(){

  }

  C* pointer;
};

class A {
public:
  A(): c(10), b(&c) {

  }

  void init() {
    t0 = std::thread(std::bind(&B::live, b));
    t1 = std::thread(std::bind(&C::live, c));
  }

  ~A() {

  }

  std::thread t0, t1;

  B b;
  C c;
};

void main() {
  A a;
  a.init();

  while (true){
    std::cout << a.b.pointer->getVal() << std::endl;
  }
}

【问题讨论】:

  • 也许 boost bind/thread 会复制绑定的实例?易于检查:阻止复制。
  • 旁注:初始化顺序由声明顺序决定 Swap B b; C c to C c; B b;
  • @DieterLücking 为什么不支持也不回答?
  • @DieterLücking 我试过了,但没有任何改变。
  • @perencia b 只取会员 c 的地址

标签: c++ boost boost-thread


【解决方案1】:

我更改了这段代码:

t0 = boost::thread(boost::bind(&B::live, b));
t1 = boost::thread(boost::bind(&C::live, c));

到:

t0 = boost::thread(std::bind(&B::live, &b));
t1 = boost::thread(std::bind(&C::live, &c));

如果你不使用指向对象的指针,它可能会复制那个对象然后运行线程。

【讨论】:

  • 默认情况下,它应该复制,但我与指针共享的对象'c'与正在更改的对象不同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多