本文介绍了使用std :: thread和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;
}

但以下列错误结束:

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

我想知道< thread> .detach()的用法是否正确?如果我使用.join()它工作,但我想让每个线程独立运行,而不是等待线程完成。
我也想知道什么是实现上述逻辑的最好方法。

I want to know if the usage of <thread>.detach() is correct above? If I use .join() it works, but I want each thread to run independently and not wait for the thread to finish.I also want to know what is the best way to achieve the above logic.

推荐答案

p>

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

不调用 detach()),你可以在最后加入他们,所以你知道他们已经完成了他们的任务。

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.

这篇关于使用std :: thread和std :: mutex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:05