我想互斥锁与独立的线程。要求是,我有许多线程可以独立运行并访问/更新常见的资源。为了确保追索权通过一项任务得到更新,我使用了互斥体。但是这不起作用。使用std :: thread与std :: mutex
我已经粘贴代码,什么我想下面要做的表示:
#include <iostream>
#include <map>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>
#include <unistd.h>
std::mutex mt;
static int iMem = 0;
int maxITr = 1000;
void renum()
{
// Ensure that only 1 task will update the variable
mt.lock();
int tmpMem = iMem;
usleep(100); // Make the system sleep/induce delay
iMem = tmpMem + 1;
mt.unlock();
printf("iMem = %d\n", iMem);
}
int main()
{
for (int i = 0; i < maxITr; i++) {
std::thread mth(renum);
mth.detach(); // Run each task in an independent thread
}
return 0;
}
但是这与下面的错误终止:
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
我想知道,如果使用<线程> .detach()是否正确?如果我使用.join()它有效,但我希望每个线程独立运行,而不是等待线程完成。 我也想知道什么是实现上述逻辑的最佳方式。
当你从'main()'返回时,进程将退出,所以线程中任何仍未完成的工作都不会完成。使用'join()'等待它们是'main()'返回之前完成的一件事情。 – 2014-10-20 04:55:33
A *千*线程似乎相当矫枉过正。试着用一些可管理的东西来解决这个问题。 (如3)。而且你并没有等待你的线程,所以只要你完成了'main()'终止线程,完成你的过程;可能*不*你想要什么。为此,我建议一个线程分离是错误的。相反,你应该将它们强加到'std :: vector <>'中,然后在'main()'终止前加入它们* all *。 – WhozCraig 2014-10-20 04:58:43
@MichaelBurr感谢您的评论。因此,如果我使用.join(),每个线程是独立运行还是等待前一个线程完成?我的要求是每个线程应该独立运行。谢谢你的帮助。 – programmer 2014-10-20 04:59:20