队列中我的未来和承诺(packaged_task)的共享状态

时间:2019-09-04 15:01:23

标签: c++ multithreading std-future

我在线程安全队列上提交(移动)std::packaged_task(在下面的示例中是std::queue,它不是线程安全的)。但是首先我返回一个std::future,以便有可能等待任务的结果。当我观察到共享状态时,我发现它是在packaged_task创建期间创建的,然后具有值1。当我得到任务的未来时,它将增加到2。当我将任务移到队列中时,共享状态仍为2。现在,在将任务从队列中弹出并执行任务的同时处理了队列。我的问题来了:任务从队列中弹出,但共享状态不变!这导致内存溢出。我该如何解决? 请注意:当我等着未来等待任务执行结束时,让未来超出范围时,共享状态将减为“ 1”。

这是我的示例代码:

void doThreadWork(unsigned long thread)
{
    std::cout << std::endl << "Thread number: " << thread << std::endl;
}

std::queue<funcWrap<void(unsigned long)>> workQueue;

int main()
{
    {
        std::packaged_task<void(unsigned long)> boundTask(
            std::bind(doThreadWork, std::placeholders::_1));  // shared state is created and has the value 1

        std::future<void> fut(boundTask.get_future());  // shared state has the value 2

        workQueue.push(std::move(boundTask)); // shared state has still the value 2

        funcWrap<void(unsigned long)> task(stl_workQueue.front());  // shared state value 2

        task(111);

        fut.wait();        
    }
    // fut is out of scope, hence shared state is now 1

    workQueue.pop(); // SHARED STATE REMAINS 1. WHY?
}

我简化了单线程案例的示例,并使用stl std :: queue简化了代码。 funcWrap<void(unsigned long)>是一个简单的函数包装器,仅具有移动功能。

这是一个相关的问题: Who is responsible for the shared state of futures and promises

谢谢。

0 个答案:

没有答案