教你Unix消息隊列的應(yīng)用
我們以前學(xué)習(xí)過Unix消息隊列的創(chuàng)建、刪除、發(fā)送和接收的知識,今天,我們來學(xué)習(xí)在線程中Unix消息隊列應(yīng)用以實現(xiàn)多任務(wù)線程間的數(shù)據(jù)共享的知識,洗大家能夠在Unix的學(xué)習(xí)上有所收獲。
首先在main主函數(shù)中創(chuàng)建Unix消息隊列和線程://定義全局變量
- Int msqueue_record, msqueue_process;
- Void main()
- {
- pthread_t pthreadID1;
- //創(chuàng)建消息隊列,用于線程間通信
- msqueue_record = msqueue_create ( “record”, 200, 200);
- msqueue_process = msqueue_create ( “process”, 200, 200);
- //創(chuàng)建數(shù)據(jù)采集線程
- pthread_create ( &&pthreadID1, NULL, receiveData, NULL);
- //創(chuàng)建數(shù)據(jù)處理線程
- pthread_create ( &&pthreadID2, NULL, process, NULL);
- //創(chuàng)建數(shù)據(jù)記錄線程
- pthread_create ( &&pthreadID1, NULL, record, NULL);
- //等待進(jìn)程結(jié)束
- wait_thread_end( );
- }
數(shù)據(jù)采集線程:
- void receiveData( )
- {
- int count;
- unsigned char buff[200];
- for(;;) {
- //從數(shù)據(jù)口采集數(shù)據(jù),并將數(shù)據(jù)放置于buff中
- //wait_data_from_data_port( buff )
- //將數(shù)據(jù)寫入消息隊列msqueue_record中
- msqueue_send ( msqueue_record, buff, 200 );
- //將數(shù)據(jù)寫入消息隊列msqueue_process中
- msqueue_send ( msqueue_process, buff, 200 );
- }
- }
記錄線程函數(shù):
- void record ( )
- {
- int num, count;
- unsigned char buffer[200];
- for ( ;; ) {
- count = msqueue_receive ( msg_record, &&buffer, 200 );
- if ( count < 0) {
- perror ( "msgrcv in record");
- continue;
- }
- //將取到的消息進(jìn)行記錄處理
- //record_message_to_lib();
- }
- }
數(shù)據(jù)處理線程函數(shù):
- int process( )
- {
- int count;
- unsigned char buffer[200];
- for ( ;; ) {
- count = msqueue_receive ( msg_process, &&buffer, 200 );
- if ( count < 0) {
- perror ( "msgrcv in record");
- continue;
- }
- //將取到的消息進(jìn)行處理
- //process_message_data()
- }
- }
在實現(xiàn)多任務(wù)系統(tǒng)時,作者曾經(jīng)做過以下三種實現(xiàn)方法的比較:進(jìn)程間通信采用IPC機制,線程間通信采用進(jìn)程通信方式IPC,線程間通信采用基于作者開發(fā)的Unix消息隊列。結(jié)果表明:利用用戶下的數(shù)據(jù)區(qū)進(jìn)行線程間通信的速度最快,效率最高,而IPC方式慢。這次,關(guān)于Unix消息隊列我們就講解到這里了。
【編輯推薦】