//--------------------------test.cpp开始-------------------------------------
//主程序文件
#include "msgdequeue.h" #include
#include
using namespace std;
CMessageDequeue qq(5);
void *get_thread(void *parg);
void *put_thread(void *parg);
void *get_thread(void *parg)
{
while(true)
...{
int a = -1;
if( !qq.pop_front( a,true, 1000 ) ) ...{ cout << "pop failed. size=" << qq.size() << endl;
}
}
return NULL;
}
void *put_thread(void *parg)
{
for(int i=1; i<=30; i++)
...{ qq.push_back( i, -1 );
}
return NULL;
}
int main()
{
pthread_t pget,pput; pthread_create( &pget,NULL,get_thread,NULL);
pthread_create( &pput, NULL, put_thread,NULL);
pthread_join( pget,NULL ); pthread_join( pput,NULL );
return 0;
}
//--------------------------test.cpp结束-------------------------------------............编译程序:g++ msgdequeue.h test.cpp -lpthread -lrt -o test -lpthread链接pthread库。-ltr链接clock_gettime函数相关库。
编译后生成可执行文件test。输入./test执行程序。
线程get_thread每隔1000毫秒从队列取元素,线程put_thread将30个元素依次入队。两个线程模拟两条入队和出队的流水线。因我们在 CMessageDequeue qq(5)处定义了队列最多可容纳5个元素,入队线程每入队到队列元素满5个后需阻塞等待出队线程将队列元素出队才能继续。测试时可调整队列可容纳最大元素个数来观察运行效果。
本文通过一个C++示例展示了如何使用多线程进行数据入队和出队操作。线程`get_thread`每隔1000毫秒尝试从队列中弹出元素,而线程`put_thread`向队列中插入30个元素。由于队列容量限制为5,当队列满时,入队线程会被阻塞,直到出队线程消费元素。这种机制演示了线程同步和队列满阻塞的基本概念。
2万+

被折叠的 条评论
为什么被折叠?



