调用方法,该方法修改字段,而使用该字段的另一个方法正在执行

Calling method that modifies a field while another method that uses that field is executing

本文关键字:方法 字段 另一个 执行 修改 调用      更新时间:2023-10-16

我有一个关于运行方法的外部修改的问题。 给定这个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;
}