gpt4 book ai didi

C++ std::async 调用类成员方法看不到变量变化

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:21:21 25 4
gpt4 key购买 nike

我对 std::async 启动的进程有一些问题。

class BaseClass {
public:
BaseClass() {enabledFlag = false;}
virtual ~BaseClass() {}

protected:
int process();
bool enabledFlag;
};


int BaseClass::process() {
int rc = -1;
if (enabledFlag == false) {
std::cout << "Not enabled\n" << std::flush;
return rc;
}

rc = 0;
while (enabledFlag) {
// this loop should set rc to be something other than zero if an error is to be signalled
// otherwise loop here doing stuff until the user sets enabledFlag=false
}

return rc;
}

class DerivedClassWithExposedMembersForTesting : public BaseClass {
public:
using BaseClass::enabledFlag;
using BaseClass::process;

};

在我的 Google Test 测试中:

TEST(FixtureName, process_exitsWithRC0_WhenEnabledFlagSetTrueDuringExecution {
DerivedClassWithExposedMembersForTesting testClass;
testClass.enabledFlag = true;

// print status
std::cout << "Enabled: " << testClass.enabledFlag << std::endl << std::flush;

std::future<int> returnCodeFuture = std::async(std::launch::async, &DerivedClassWithExposedMembersForTesting::process, &testClass); // starts background execution
// set flag to false to kill loop
testClass.enabledFlag = false;

int rc = returnCodeFuture.get();

EXPECT_EQ(0, rc);
}

我对 std::async 的理解是,它应该被安排在调用 async 后不久运行,如果线程尚未完成,则执行的主线程将在 get() 调用时阻塞。调用 get() 将返回 process() 的返回值。

如果未启用 testClass,process() 将设置为不运行,因此我在测试中启用它。

我希望看到:

Enabled: 1
// test passes

我看到的是:

Enabled: 1
Not enabled
// test fails
Failure
Value of: rc
Actual: -1
Expected: 0

为什么由 std::async 触发的进程看不到主进程在进行异步调用之前设置的 enabledFlag 的值?

注意:enabledFlag 应该从外部进程设置,而不是通常从循环内设置,因此这种构造

** 更新 **根据我的评论,我通过在调用 async() 之后向测试添加以下行来修复它:

// Use wait_for() with zero milliseconds to check thread status; delay until it has started
while (returnCodeFuture.wait_for(std::chrono::milliseconds(0)) == std::future_status::deferred) {}

最佳答案

问题是您不知道什么时候线程会运行。可能是您在线程实际运行之前简单地将标志设置为 false

解决这个问题的一个简单方法是使用另一个状态变量,isRunning,线程在循环内设置它。您的主线程可以检查它以了解线程何时运行,然后告诉它结束。

关于C++ std::async 调用类成员方法看不到变量变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25808923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com