C++で、queueにデータがpushされたことを監視する方法って、どんなものがありますか?
いま、わたしが実装しているのは、whileによる無限ループで、ループ毎にqueueからpopするようにしています。
この方法だと、冗長だという気がしてなりません。
FDを監視するselectみたいなものは、ありませんでしょうか?
コードを以下に掲載します。
msg_receive()のなかで、whileループでメッセージキュー(msgq)を監視しているところを改善したいです。
c++
1#include <iostream> 2#include <cstdlib> 3#include <unistd.h> 4#include <fcntl.h> 5#include <pthread.h> 6#include <string> 7#include <queue> 8 9using namespace std; 10 11queue<string> msgq; 12pthread_mutex_t msgmutex = PTHREAD_MUTEX_INITIALIZER; 13 14// メッセージ受信 15void *msg_receive(void *arg){ 16 while(true){ 17 if(!msgq.empty()){ 18 pthread_mutex_lock(&msgmutex); 19 cout << " Receive Thread pop data : " << msgq.front() << endl; 20 msgq.pop(); 21 pthread_mutex_unlock(&msgmutex); 22 usleep(1500000); // 1.5秒 23 } 24 } 25 pthread_exit((void *)0); 26} 27 28// メッセージ送信 29void *msg_send(void *arg) { 30 string msg; 31 32 while(true){ 33 cin >> msg; 34 pthread_mutex_lock(&msgmutex); 35 msgq.push(msg); 36 pthread_mutex_unlock(&msgmutex); 37 } 38 pthread_exit((void *)0); 39} 40 41int main(int argc, char **argv) { 42 pthread_t thr1, thr2; 43 44 // 受信スレッド、送信スレッドを生成 45 if(pthread_create(&thr1, NULL, msg_receive, NULL) || 46 pthread_create(&thr2, NULL, msg_send, NULL)){ 47 cout << argv[0] << "qthread_create() is failed\n"; 48 exit(1); 49 } 50 51 // スレッドの終了を待つ 52 pthread_join(thr1, NULL); 53 pthread_join(thr2, NULL); 54 return 0; 55}
回答3件
あなたの回答
tips
プレビュー