stl的queue到底是不是线程安全的?
JQ123 2007-05-15 11:27:00 在网上看到不少人说stl容器不是线程安全的,谁能举个例子?我有个需求是两个线程对一个queue同时进行读写操作,我写下面的代码测试了一下没有问题呀?
#include "ace/Task.h"
#include <queue>
#include <iostream>
#include <assert.h>
#include <ace/OS.h>
using namespace std;
queue<int> g_Queue;
bool g_bEnd = false;
bool g_bEnd2 = false;
ACE_Time_Value t(0);
class Consumer : public ACE_Task_Base
{
public:
Consumer()
{
//this->m_Queue = q;
}
int svc()
{
int last = -1;
t.usec(100);
while(!g_bEnd)
{
while(!g_Queue.empty())
{
assert(g_Queue.front() == last + 1);
cout<<"Dequeue:"<<g_Queue.front()<<endl;
last = g_Queue.front();
g_Queue.pop();
}
ACE_OS::sleep(t);
}
g_bEnd2 = true;
return 0;
}
protected:
//queue<int> *m_Queue;
private:
};
class Producer : public ACE_Task_Base
{
public:
Producer(int nCount)
{
//this->m_Queue = q;
this->m_nCount = nCount;
}
int svc()
{
int last = -1;
t.usec(100);
for (int i = 0; i < this->m_nCount; ++i)
{
assert(i == last + 1);
TRACE("Enqueue:%d\n", i);
g_Queue.push(i);
last = i;
ACE_OS::sleep(t);
}
g_bEnd = true;
return 0;
}
protected:
//queue<int> *m_Queue;
int m_nCount;
private:
};
int main(int, ACE_TCHAR *[])
{
Consumer tc;
Producer tp(9999);
tc.activate();
tp.activate();
while (!g_bEnd2 || !g_bEnd)
{
ACE_OS::sleep(1);
}
return 0;
}