c++ - 将 std::thread 与 std::mutex 一起使用

标签 c++ multithreading join concurrency detach

我正在尝试使用独立线程进行互斥锁。要求是,我有许多线程将独立运行并访问/更新公共(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

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

最佳答案

试试这个:

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/

相关文章:

r - R 数据表中最近的 "n"滚动连接

android - 我如何在 SQlite/PDO 中连接表、同时聚合并将结果转换为 JSON?

java - Android:runOnUiThread并不总是选择正确的线程?

c++ - 开始 Sprite C++ DirectX

C++虚拟继承内存布局

c++ - c++中new的返回类型是什么?

linux - 使用 bash 停止时间并启动多个程序

c++ - C++ 中线程管理和工作分配的可能框架/想法

sql - 即使为 0,也返回 count(*)

c++ - 带有类型比较的 LLVM 测试示例问题