调用方法,该方法修改字段,而使用该字段的另一个方法正在执行
Calling method that modifies a field while another method that uses that field is executing
我有一个关于运行方法的外部修改的问题。 给定这个C++类:
#include <iostream>
class Foo {
public:
Foo()
: runBar(true) {}
void bar() {
int i = 0;
while(this->runBar) {
std::cout << "Loop " << i++ << std::endl;
}
std::cout << "Loop done!" << std::endl;
}
void baz() {
this->runBar = false;
std::cout << "Field changed!" << std::endl;
}
private:
bool runBar;
};
并且还给出了这个main
函数:
int main(int argc, char* argv[]) {
Foo f;
f.bar();
f.baz();
return 0;
}
拨打Foo::baz()
时会发生什么? 感谢您的帮助!
由于您只有 1 个执行线程,并且您没有任何内容可以更改bar
函数中的while
循环退出条件,因此此代码将永远循环。永远不会调用您的baz
函数。
假设你打算从单独的线程调用它们, 下面是一个示例,显示 main 修改后从线程中调用函数。 Foo使用mutext来协调活动,例如允许线程在终止之前完成打印。 联接可防止 main 终止过早结束所有内容。 如果你不以某种方式协调它们,就不可能肯定地说出事件的顺序是什么。这就是使用多个线程编程的本质。
要么在打印的情况下先运行柱线,要么 baz 先运行,在这种情况下柱线不会运行。 两者都是可能的。
#include <iostream>
#include <mutex>
mutex aMutex; //<--
class Foo {
public:
Foo()
: runBar(true) {}
void bar() {
int i = 0;
while(this->runBar) {
aMutex.lock(); //<--
std::cout << "Loop " << i++ << std::endl;
aMutex.unlock(); //<--
}
std::cout << "Loop done!" << std::endl;
}
void baz() {
this->runBar = false;
aMutex.lock(); //<--
std::cout << "Field changed!" << std::endl;
aMutex.unlock(); //<--
}
private:
bool runBar;
};
#include <thread>
int main(int argc, char* argv[]) {
Foo f;
thread myThread { f.bar() }; //call it in a thread
f.baz();
myThread.join(); //<--
return 0;
}
相关文章:
- 使用同一类中的方法重新分配字段时出现问题
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 对象引用中的字段以不同的方法返回不同的值
- 在类中定义数组的方法和字段
- 有什么方法可以"factor out"公共字段以节省空间?
- 如何从具有多个对象/字段的类中调用方法函数
- C 将方法和字段带入外部范围,而无需明确的参考
- 使用静态方法初始化 const 类字段的做法是好是坏
- 从CSV文件中提取每个条目字段的最佳方法是什么
- 使用某些"specialized"字段调用继承的方法
- 修复警告"field a is not used"如果字段在配置中未使用的好方法
- 使用方法影响另一个对象的字段
- 调用方法,该方法修改字段,而使用该字段的另一个方法正在执行
- 安全的方法来为char []字段创建Getter
- 修改Boost多索引项的非索引字段的最佳方法:modify vs mutable
- C :初始化成员结构的静态字段的正确方法
- 为什么 c++ 中没有重复的 protobuf 字段的 Set 方法
- C++ - 有没有办法将字段\方法添加到使用"typedef"定义的类型?
- 类方法或字段
- 使用静态方法/字段 c++ 进行继承