简体   繁体   English

在std :: mutex中使用std :: thread

[英]Using std::thread with std::mutex

I am trying mutex lock with independent threads. 我正在尝试使用独立线程进行互斥锁。 The requirement is, I have many threads which will run independently and access/update a common recourse. 要求是,我有许多线程将独立运行并访问/更新公共资源。 To ensure that the recourse is updated via a single task, I used mutex. 为了确保通过单个任务更新资源,我使用了互斥锁。 However this is not working. 但是,这不起作用。

I have pasted code, a representation of what I am trying to do below: 我粘贴了代码,下面是我想要做的事情的表示形式:

#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;
}

but this is terminating with the below error: 但这终止于以下错误:

terminate called after throwing an instance of 'std::system_error'
  what():  Resource temporarily unavailable

I want to know if the usage of <thread>.detach() is correct above? 我想知道<thread> .detach()的用法在上面是否正确? If I use .join() it works, but I want each thread to run independently and not wait for the thread to finish. 如果我使用.join()可以工作,但是我希望每个线程独立运行,而不要等待线程完成。 I also want to know what is the best way to achieve the above logic. 我也想知道实现上述逻辑的最佳方法是什么。

Try this: 尝试这个:

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();
  }
}

This way, you retain control of the threads (by not calling detach() ), and you can join them all at the end, so you know they have completed their tasks. 这样,您就可以保留对线程的控制(不调用detach() ),并且可以在最后将它们全部加入,因此您知道它们已经完成了任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM