gpt4 book ai didi

c++ - 如何在 std::queue 中存储 char 缓冲区

转载 作者:行者123 更新时间:2023-11-28 07:17:32 26 4
gpt4 key购买 nike

我有一个有 2 个线程的 udp 客户端。
从套接字接收到的数据被放入队列中,由第二个线程处理。

执行此操作的正确方法是什么?
它是否正确?

案例一

char* buffer = new char[1024];
Receive the socket data in buffer
Lock mutex
_queue.push_back(buffer)
signal the waiting thread
Unlock mutex

//In second thread
while(1)
while(queue not empty)
Lock mutex
const char* buf = _queue.front()
_queue.pop();
Unlock mutex
...
Some strtok actions on buf **(This is causing crash)**
...
delete[] buf //Removing this line removes crash
conditional wait

最佳答案

标准 C++ 容器不是线程安全的。您需要在对队列的访问周围设置某种阻塞,否则 front() 很可能返回无效指针。

关于c++ - 如何在 std::queue 中存储 char 缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20003768/

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