作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在 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/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!