C++ 中的队列和线程

Mic*_*ael 0 c++ queue multithreading

我试图做什么:

我试图使程序的目标是将元素添加到队列(在线程中)并显示有关队列的数据(您可以在主窗口中看到要显示的数据)。在此之前,我想从队列中删除一个元素(每两秒)并添加新元素(每一秒)。

代码

#include <iostream>
#include <queue>
#include <thread>
#include <Windows.h>

using std::queue;
using std::cout;

void loadQueue(queue<int> &toLoad)
{
    for(int i = 0; i < 100; i++)
    {
        toLoad.push(i); 
        Sleep(1000);
    }
}

int main(void)
{
    queue<int>toLoad;
    std::thread(loadQueue, std::ref(toLoad));

    while(true)
    {
        cout << "SIZE OF QUEUE : " << toLoad.size() << '\n' << '\n'; 

        cout <<"FRONT :" << toLoad.front() << '\n' << '\n';

        cout <<"BACK : " << toLoad.back() << '\n';
        toLoad.pop();
        Sleep(2000);
    }

}
Run Code Online (Sandbox Code Playgroud)

关于错误

当我启动程序时,我什么也看不到。程序立即关闭。Visual Studio 向我显示此消息:

启动程序后 VISUAL STUDIO 代码显示错误

The*_*ind 7

std::thread当它附加到执行线程时不能被销毁。然而,在您的情况下,您在这行代码中引入了一个临时变量,该临时变量在表达式完成时被销毁:

std::thread(loadQueue, std::ref(toLoad));
Run Code Online (Sandbox Code Playgroud)

您要么需要分离线程并让它成为:

std::thread{ loadQueue, std::ref(toLoad) }.detach();
Run Code Online (Sandbox Code Playgroud)

或者在工作进行时命名变量并使其保持活动状态:

std::thread thread{ loadQueue, std::ref(toLoad) };
Run Code Online (Sandbox Code Playgroud)

由于主线程中有无限循环,因此该线程永远不会被销毁,但理想情况下您希望将其加入某个地方,例如在函数末尾main

while(true)
{
   ... 
}
thread.join();
Run Code Online (Sandbox Code Playgroud)

另请注意,这std::queue不是一个线程安全的类,因此您必须手动同步对它的访问,否则您的代码中会存在竞争条件,按照标准,这是 UB 的。