std::async 似乎没有使用 std::launch::async 生成线程
std::async doesn't seem to spawn thread with std::launch::async
我正在编写一个DCPU-16模拟器,我正在通过启动一个线程来计算CPU的实时时钟速度,该线程在单独的线程中调用函数getRealTimeCPUClock()。 问题是,即使 future 对象的"valid"属性没有返回值,它似乎也是真的。 因此,当调用 futureObj.get() 时,它会等待 getRealTimeCPUClock() 返回。
使用异步(而不是延迟)的启动策略,它不应该在后台启动函数,然后在返回时将有效属性设置为 true?
这是错误的用法吗?
int getRealTimeCPUClock() {
int cyclesBeforeTimer = totalCycles;
sleep(1);
return totalCycles - cyclesBeforeTimer;
}
void startExecutionOfProgram(char *programFileName)
{
size_t lengthOfProgramInWords = loadProgramIntoRAM(programFileName);
auto futureRealTimeClockSpeed = std::async(std::launch::async, getRealTimeCPUClock);
while(programCounter < lengthOfProgramInWords) {
if(futureRealTimeClockSpeed.valid()) {
realTimeClockSpeed = futureRealTimeClockSpeed.get();
futureRealTimeClockSpeed = std::async(std::launch::async, getRealTimeCPUClock);
}
step();
}
}
valid()
并没有你认为的那样(尽管cpp首选项中的条目表明并非如此)。
以下是标准对valid()
的规定:
(§ 30.6.6/18) bool valid() const noexcept;
返回:仅当 *这是指共享状态时,才为 true。
只要future
对象与有效的共享状态相关联,valid()
返回的值就会被true
,这通常是在使用std::async
启动它之后和检索结果之前(使用 get()
)。当您使用 share()
方法创建shared_future
时,future
也将失效。这些都与您尝试执行的操作无关,即检查结果是否可用。
为了确定future
的结果是否准备就绪,我建议使用延迟为 0 的 wait_for()
函数:
if (futureRealTimeClockSpeed.wait_for(std::chrono::seconds(0))
== std::future_status::ready)
/*...*/
相关文章:
- 为什么std::async使用同一个线程运行函数
- 为什么可以将左值传递给"std::async",即使它引用了右值
- 使用 std::async 时死锁,将来作为成员
- 为什么我不能将引用作为 std::async 的函数参数传递
- std::async from std::async in windows xp
- std::async 如何工作:为什么它会调用这么多次复制/移动?
- std::async 不会立即调用
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- 可能的 std::async 实现错误 Windows
- C++从 std::async 函数读取命名空间中的全局变量标志
- std::async 究竟是如何执行的?
- 使用 g++8 和 c++20 的 std::async 编译问题
- 如何有效地使用 std::async 对指针数组执行操作
- 如何从 std::async 任务返回 std::tuple
- 使用 std::bind 将 QTimer::singleShot 传递给 std::async
- 如何将函数及其参数传递给成员函数内的 std::async
- 从 VS2013 到 VS2017 std::async 不会启动新线程
- 使用 std::async 调用模板函数的正确方法是什么?
- C++ - 使用 std::async 时显示进度条
- Clang 崩溃,在 std::async 中出现字符 * 异常