欢迎访问生活随笔!

生活随笔

您现在的位置是:首页 > 形式科学 > 操作系统 > 其他OS

其他OS

教你Unix消息队列的应用

发布时间:2022-09-30其他OS 系统管理员
我们在以前的文章中已经介绍过了Unix消息队列的创建、删除、发送和接收的知识,这次,我们来介绍下在线程中Unix消息队列应用的知识。

我们以前学习过Unix消息队列的创建、删除、发送和接收的知识,今天,我们来学习在线程中Unix消息队列应用以实现多任务线程间的数据共享的知识,洗大家能够在Unix的学习上有所收获。

首先在main主函数中创建Unix消息队列和线程://定义全局变量

  1. Intmsqueue_record,msqueue_process;
  2. Voidmain()
  3. {
  4. pthread_tpthreadID1;
  5. //创建消息队列,用于线程间通信
  6. msqueue_record=msqueue_create(“record”,200,200);
  7. msqueue_process=msqueue_create(“process”,200,200);
  8. //创建数据采集线程
  9. pthread_create(&&pthreadID1,NULL,receiveData,NULL);
  10. //创建数据处理线程
  11. pthread_create(&&pthreadID2,NULL,process,NULL);
  12. //创建数据记录线程
  13. pthread_create(&&pthreadID1,NULL,record,NULL);
  14. //等待进程结束
  15. wait_thread_end();
  16. }


数据采集线程:

  1. voidreceiveData()
  2. {
  3. intcount;
  4. unsignedcharbuff[200];
  5. for(;;){
  6. //从数据口采集数据,并将数据放置于buff中
  7. //wait_data_from_data_port(buff)
  8. //将数据写入消息队列msqueue_record中
  9. msqueue_send(msqueue_record,buff,200);
  10. //将数据写入消息队列msqueue_process中
  11. msqueue_send(msqueue_process,buff,200);
  12. }
  13. }

记录线程函数:

  1. voidrecord()
  2. {
  3. intnum,count;
  4. unsignedcharbuffer[200];
  5. for(;;){
  6. count=msqueue_receive(msg_record,&&buffer,200);
  7. if(count<0){
  8. perror("msgrcvinrecord");
  9. continue;
  10. }
  11. //将取到的消息进行记录处理
  12. //record_message_to_lib();
  13. }
  14. }

数据处理线程函数:

  1. intprocess()
  2. {
  3. intcount;
  4. unsignedcharbuffer[200];
  5. for(;;){
  6. count=msqueue_receive(msg_process,&&buffer,200);
  7. if(count<0){
  8. perror("msgrcvinrecord");
  9. continue;
  10. }
  11. //将取到的消息进行处理
  12. //process_message_data()
  13. }
  14. }

在实现多任务系统时,作者曾经做过以下三种实现方法的比较:进程间通信采用IPC机制,线程间通信采用进程通信方式IPC,线程间通信采用基于作者开发的Unix消息队列。结果表明:利用用户下的数据区进行线程间通信的速度最快,效率最高,而IPC方式慢。这次,关于Unix消息队列我们就讲解到这里了。

【编辑推荐】

  1. 教你如何创建Unix消息队列
  2. 知识讲堂Unix内核教学
  3. 初步讲解Unix 线程知识
  4. 探析Unix操作系统启动
  5. 知识讲解Unix 消息队列