教你Unix消息队列的应用
我们在以前的文章中已经介绍过了Unix消息队列的创建、删除、发送和接收的知识,这次,我们来介绍下在线程中Unix消息队列应用的知识。
我们以前学习过Unix消息队列的创建、删除、发送和接收的知识,今天,我们来学习在线程中Unix消息队列应用以实现多任务线程间的数据共享的知识,洗大家能够在Unix的学习上有所收获。
首先在main主函数中创建Unix消息队列和线程://定义全局变量
- Intmsqueue_record,msqueue_process;
- Voidmain()
- {
- pthread_tpthreadID1;
- //创建消息队列,用于线程间通信
- msqueue_record=msqueue_create(“record”,200,200);
- msqueue_process=msqueue_create(“process”,200,200);
- //创建数据采集线程
- pthread_create(&&pthreadID1,NULL,receiveData,NULL);
- //创建数据处理线程
- pthread_create(&&pthreadID2,NULL,process,NULL);
- //创建数据记录线程
- pthread_create(&&pthreadID1,NULL,record,NULL);
- //等待进程结束
- wait_thread_end();
- }
数据采集线程:
- voidreceiveData()
- {
- intcount;
- unsignedcharbuff[200];
- for(;;){
- //从数据口采集数据,并将数据放置于buff中
- //wait_data_from_data_port(buff)
- //将数据写入消息队列msqueue_record中
- msqueue_send(msqueue_record,buff,200);
- //将数据写入消息队列msqueue_process中
- msqueue_send(msqueue_process,buff,200);
- }
- }
记录线程函数:
- voidrecord()
- {
- intnum,count;
- unsignedcharbuffer[200];
- for(;;){
- count=msqueue_receive(msg_record,&&buffer,200);
- if(count<0){
- perror("msgrcvinrecord");
- continue;
- }
- //将取到的消息进行记录处理
- //record_message_to_lib();
- }
- }
数据处理线程函数:
- intprocess()
- {
- intcount;
- unsignedcharbuffer[200];
- for(;;){
- count=msqueue_receive(msg_process,&&buffer,200);
- if(count<0){
- perror("msgrcvinrecord");
- continue;
- }
- //将取到的消息进行处理
- //process_message_data()
- }
- }
在实现多任务系统时,作者曾经做过以下三种实现方法的比较:进程间通信采用IPC机制,线程间通信采用进程通信方式IPC,线程间通信采用基于作者开发的Unix消息队列。结果表明:利用用户下的数据区进行线程间通信的速度最快,效率最高,而IPC方式慢。这次,关于Unix消息队列我们就讲解到这里了。
【编辑推荐】
- 教你如何创建Unix消息队列
- 知识讲堂Unix内核教学
- 初步讲解Unix 线程知识
- 探析Unix操作系统启动
- 知识讲解Unix 消息队列
- 上一篇:学习简单的Unix信号量
- 下一篇:教你如何创建Unix消息队列