gpt4 book ai didi

c++ - 将 vector 存储和写入队列c++

转载 作者:行者123 更新时间:2023-12-02 10:11:15 25 4
gpt4 key购买 nike

#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);
}

}
发生以下错误
vector 下标超出范围 1501 错误
在线程函数中间
让它休眠(2),它有时会起作用,但很快我就会出错。
如果 vector 是问题,有没有其他方法可以将数组存储在队列中?
我不知道问题出在哪里
有什么好办法吗?

最佳答案

您根本无法以如此简单的方式做到这一点。如果您希望一个线程从队列中挑选由另一个线程写入的消息,您需要 mtuexes 和条件变量。这不是一项微不足道的任务。我建议很多谷歌搜索。如果我找到一个好的链接,我也会在这里查看并更新
https://juanchopanzacpp.wordpress.com/2013/02/26/concurrent-queue-c11/
https://gist.github.com/ictlyh/f8473ad0cb1008c6b32c41f3dea98ef5

关于c++ - 将 vector 存储和写入队列c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63480110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com