小编Mik*_*ike的帖子

std::thread 抛出“将发生资源死锁”

我有一个对象列表,每个对象都有由“更新”函数计算的成员变量。我想并行更新对象,即我想为每个对象创建一个线程来执行它的更新功能。

这是一个合理的做法吗?这可能不是一个好主意的任何原因?

下面是一个尝试执行我所描述的程序的程序,这是一个完整的程序,因此您应该能够运行它(我使用的是 VS2015)。目标是并行更新每个对象。问题是一旦更新函数完成,线程就会抛出“将发生资源死锁”异常并中止。

我哪里错了?

#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <thread>
#include <mutex>
#include <chrono>

class Object 
{
public:

    Object(int sleepTime, unsigned int id)
        : m_pSleepTime(sleepTime), m_pId(id), m_pValue(0) {}

    void update()
    {
        if (!isLocked()) // if an object is not locked
        {
            // create a thread to perform it's update
            m_pThread.reset(new std::thread(&Object::_update, this));
        }
    }

    unsigned int getId()
    {
        return m_pId;
    }

    unsigned int getValue()
    {
        return m_pValue;
    }

    bool isLocked()
    {
        bool mutexStatus = m_pMutex.try_lock(); …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading stdthread

0
推荐指数
1
解决办法
1847
查看次数

标签 统计

c++ ×1

multithreading ×1

stdthread ×1