我正在尝试使用独立线程进行互斥锁。要求是,我有许多线程将独立运行并访问/更新公共(public)资源。为了确保通过单个任务更新资源,我使用了互斥体。然而这不起作用。
我已经粘贴了代码,代表了我在下面尝试做的事情:
#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
我想知道上面
最佳答案
试试这个:
int main()
{
std::vector<std::thread> mths;
mths.reserve(maxITr);
for (int i = 0; i < maxITr; i++) {
mths.emplace_back(renum);
}
for (auto& mth : mths) {
mth.join();
}
}
这样,您就可以保留对线程的控制(通过不调用detach()
),并且您可以在最后将它们全部连接起来,这样您就知道它们已经完成了任务。
关于c++ - 将 std::thread 与 std::mutex 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458753/