質問編集履歴

1

誤記

2018/12/30 06:27

投稿

torimingo
torimingo

スコア122

test CHANGED
File without changes
test CHANGED
@@ -5,3 +5,123 @@
5
5
  この方法だと、冗長だという気がしてなりません。
6
6
 
7
7
  FDを監視するselectみたいなものは、ありませんでしょうか?
8
+
9
+
10
+
11
+ コードを以下に掲載します。
12
+
13
+ msg_receive()のなかで、whileループでメッセージキュー(msgq)を監視しているところを改善したいです。
14
+
15
+ ```c++
16
+
17
+ #include <iostream>
18
+
19
+ #include <cstdlib>
20
+
21
+ #include <unistd.h>
22
+
23
+ #include <fcntl.h>
24
+
25
+ #include <pthread.h>
26
+
27
+ #include <string>
28
+
29
+ #include <queue>
30
+
31
+
32
+
33
+ using namespace std;
34
+
35
+
36
+
37
+ queue<string> msgq;
38
+
39
+ pthread_mutex_t msgmutex = PTHREAD_MUTEX_INITIALIZER;
40
+
41
+
42
+
43
+ // メッセージ受信
44
+
45
+ void *msg_receive(void *arg){
46
+
47
+ while(true){
48
+
49
+ if(!msgq.empty()){
50
+
51
+ pthread_mutex_lock(&msgmutex);
52
+
53
+ cout << " Receive Thread pop data : " << msgq.front() << endl;
54
+
55
+ msgq.pop();
56
+
57
+ pthread_mutex_unlock(&msgmutex);
58
+
59
+ usleep(1500000); // 1.5秒
60
+
61
+ }
62
+
63
+ }
64
+
65
+ pthread_exit((void *)0);
66
+
67
+ }
68
+
69
+
70
+
71
+ // メッセージ送信
72
+
73
+ void *msg_send(void *arg) {
74
+
75
+ string msg;
76
+
77
+
78
+
79
+ while(true){
80
+
81
+ cin >> msg;
82
+
83
+ pthread_mutex_lock(&msgmutex);
84
+
85
+ msgq.push(msg);
86
+
87
+ pthread_mutex_unlock(&msgmutex);
88
+
89
+ }
90
+
91
+ pthread_exit((void *)0);
92
+
93
+ }
94
+
95
+
96
+
97
+ int main(int argc, char **argv) {
98
+
99
+ pthread_t thr1, thr2;
100
+
101
+
102
+
103
+ // 受信スレッド、送信スレッドを生成
104
+
105
+ if(pthread_create(&thr1, NULL, msg_receive, NULL) ||
106
+
107
+ pthread_create(&thr2, NULL, msg_send, NULL)){
108
+
109
+ cout << argv[0] << "qthread_create() is failed\n";
110
+
111
+ exit(1);
112
+
113
+ }
114
+
115
+
116
+
117
+ // スレッドの終了を待つ
118
+
119
+ pthread_join(thr1, NULL);
120
+
121
+ pthread_join(thr2, NULL);
122
+
123
+ return 0;
124
+
125
+ }
126
+
127
+ ```