存储向量并将其写入队列c++


#include <iostream>
#include <queue>
#include <thread>
#include <process.h>
#include <windows.h>
#include <stdlib.h>
int g_Width = 100;
std::queue<std::vector<unsigned short>> BufferQueue;
bool dataRead = false;
unsigned short* g_pImgBuf = NULL;

unsigned int _stdcall Write(void* arg) {

std::vector<unsigned short> data;
data.reserve(g_Width);

int line = 0;
while (dataRead)
{
if (!dataRead)
break;
for (int i = 0; i < g_Width; i++) {
data.push_back(i);    
}

BufferQueue.push(data);
data.clear();
}
_endthreadex(0);
return 0;
}
unsigned  int _stdcall Read(void* arg) {

std::vector<unsigned short> data;
data.reserve(g_Width);

unsigned short color = 0;
int line = 0;
while (dataRead)
{
g_pImgBuf = new unsigned short[g_Width];

if (!BufferQueue.empty()) {
data = BufferQueue.front();
BufferQueue.pop();
}
else if (!dataRead)
break;
else {
continue;
}

for (int j = 0; j < g_Width; j++) {
color = data[j];
color += 2;
g_pImgBuf[j] = color;
}
data.clear();
}

if (g_pImgBuf) { free(g_pImgBuf); g_pImgBuf = NULL; }

_endthreadex(0);
return 0;
}

int main()
{
dataRead = true;
HANDLE r_hThread = NULL;
unsigned  r_threadID;
r_hThread = (HANDLE)_beginthreadex(NULL, 0, Read, NULL, 0, &r_threadID);
HANDLE w_hThread = NULL;
unsigned  w_threadID;
w_hThread = (HANDLE)_beginthreadex(NULL, 0, Write, NULL, 0, &w_threadID);


while (true)
{
Sleep(100);
}
}

出现以下错误矢量下标超出范围1501错误

在线程函数的中间给它睡眠(2(,它有时有效,但很快我就出错了。

如果向量是问题所在,有没有其他方法可以将数组存储在队列中?

我不知道的问题出在哪里

有什么好办法吗?

您根本无法用如此简单的方式来实现这一点。如果您希望一个线程从队列中挑选另一个线程正在编写的消息,则需要mtuex和条件变量。这不是一项琐碎的任务。我建议多用谷歌搜索。如果我找到一个好的链接,我也会在这里查找和更新

https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/

https://gist.github.com/ictlyh/f8473ad0cb1008c6b32c41f3dea98ef5

最新更新