C++ message queue 消息隊列入門

說明
當咱們有多個線程以不一樣的速度運行而且咱們想要以特定的順序從一個線程向另外一個線程發送信息時,消息隊列可能會有用。

這個想法是,發送線程將消息推送到隊列中,而接收線程將消息按本身的步調彈出。 只要發送線程平均發送的消息不超過接收線程能夠處理的數量,此係統就能夠工做。 由於隊列充當緩衝區,因此消息可能會突發發送和彈出,換句話說:只要一段時間內的平均發送速度低於接收者的容量,流量就會達到峯值。
ios


例程
該示例顯示了一個輸入線程,該線程從控制檯(cin)讀取數據並將其推送到消息隊列中。 另外一個線程(接收方)檢查隊列大小,若是該大小不爲零,則將消息彈出隊列,並像處理該消息同樣工做。
測試

打開Qt Creator,新建控制檯應用程序,選擇MingW構建組件this

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
 
 # ifndef MSGQUEUE_H
 # define MSGQUEUE_H
 
 # include < iostream >
 # include < cstdlib >
 # include < unistd.h >  // usleep
 # include < fcntl.h >  // threads
 # include < pthread.h >
 # include < string > 
// messages
 # include < queue >  // the message queue
 
 
using   namespace  std;
 
 pthread_mutex_t msgmutex = PTHREAD_MUTEX_INITIALIZER;
 
 queue < string > msgq;
 
 
void  *msgreceiver( void  *arg)
 {
     
long  qsize;
     string nextmsg;
     
while  ( true )
     {
         
if  (msgq.empty())
         {
             usleep(
10000 );  // sleep 0.01 sec before trying again
              continue ;
         }
 
         
// we end up here because there was something in the msg queue
         pthread_mutex_lock( & msgmutex);
         qsize = msgq.size();
         
if  (qsize >  5 )
             cout << 
"Queue size: "  << qsize << endl;
         nextmsg = msgq.front(); 
// get next message in queue
         msgq.pop();  // remove it from the queue
         pthread_mutex_unlock( & msgmutex);
 
         cout << 
"Processing value "  << nextmsg << endl;
         usleep(
2000000 );
     }
     pthread_exit((
void  * ) 0 );
 } 
// msgreceiver()
 
 
void  *msgtransmitter( void  *arg)
 {
     string nextmsg;
     
while  ( true )
     {
         cin >> nextmsg;
         pthread_mutex_lock( & msgmutex);
         msgq.push(nextmsg); 
// push message onto the queue
         pthread_mutex_unlock( & msgmutex);
     }
     pthread_exit((
void  * ) 0 );
 } 
// msgtransmitter()
 
 
int  test_msgqueue()
 {
     pthread_t thr;
 
     
// Create threads
      if  (pthread_create( & thr,  NULL , msgreceiver,  NULL ) ||
             pthread_create( & thr, 
NULL , msgtransmitter,  NULL ))
     {
         cout << 
" cannot make thread\n" ;
         exit(
1 );
     }
 
     
/*
      * At this point the main thread can perform its actions or end
      */

     cout << 
"** Main thread ends **\n" ;
     pthread_exit((
void  * ) 0 );
 
 }
 
 # endif 
// MSGQUEUE_H

測試截圖spa

相關文章
相關標籤/搜索