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

时间:2013-11-15 14:49:04

标签: c++ multithreading pointers queue buffer

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

这样做的正确方法是什么?
它是否正确?

案例1

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

2 个答案:

答案 0 :(得分:1)

标准C ++容器不是线程安全的。你需要对队列的访问进行某种阻塞,否则front()很可能会返回一个无效的指针。

答案 1 :(得分:0)

第一期:崩溃 如果删除删除指令,崩溃应该消失,因为pop返回值并从队列末尾删除指针。

第二期:内存泄漏

您实际上并没有删除数据,只是指针,因此当您删除指针时,您实际上是孤立数据,从而导致内存泄漏。

如果您可以发布一些代码,我可以提供更多帮助:)