【发布时间】: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 ctoC c; B b; -
@DieterLücking 为什么不支持也不回答?
-
@DieterLücking 我试过了,但没有任何改变。
-
@perencia b 只取会员 c 的地址
标签: c++ boost boost-thread