gpt4 book ai didi

c++ - 在 C++ 中向主线程报告线程进度

转载 作者:太空狗 更新时间:2023-10-29 20:05:30 24 4
gpt4 key购买 nike

在 C/C++ 中,我怎样才能使线程(POSIX pthreads/Windows 线程)给我一个安全的方法来将执行进度或我决定执行的工作的进度传回主线程用线。

是否可以按百分比报告进度?

最佳答案

我将假设一个非常简单的主线程和一个函数的情况。我建议在每次启动线程时传递一个指向原子的指针(如上面 Kirill 所建议的)。假设这里是 C++11。

using namespace std;

void threadedFunction(atomic<int>* progress)
{
for(int i = 0; i < 100; i++)
{
progress->store(i); // updates the variable safely
chrono::milliseconds dura( 2000 );
this_thread::sleep_for(dura); // Sleeps for a bit
}
return;
}

int main(int argc, char** argv)
{
// Make and launch 10 threads
vector<atomic<int>> atomics;
vector<thread> threads;
for(int i = 0; i < 10; i++)
{
atomics.emplace_back(0);
threads.emplace_back(threadedFunction, &atomics[i]);
}

// Monitor the threads down here
// use atomics[n].load() to get the value from the atomics
return 0;
}

我想那会做你想做的。我省略了轮询线程,但你明白了。我传入了一个主线程和子线程都知道的对象(在本例中为 atomic<int> 变量),它们都可以更新和/或轮询结果。如果您没有使用完整的 C++11 线程/原子支持编译器,请使用您的平台决定的任何内容,但总有一种方法可以将变量(至少是 void* )传递到线程函数中。这就是您如何获得通过非静态来回传递信息的方法。

关于c++ - 在 C++ 中向主线程报告线程进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12984766/

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