編寫乙個具有3個子執行緒的程式,thread 1從標準輸入裝置獲取乙個字串,並將該字串傳送到訊息佇列;thread 2 從訊息佇列獲取該字串,並將其反轉,然後重新傳送到訊息佇列;thread 3讀取thread 2 傳送的訊息字串,並將字串中的大寫字元變為小寫,小寫字元變為大寫;將最終字串最為結束狀態,返回到主線程。主線程顯示thread 3的退出狀態。
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define max_text 512
struct msg_st
; static
void thread_one(char* msg);
static
void thread_two(char* msg);
static
void thread_three(char* msg);
int main(int argc, char** ar**)
sleep(3);
printf("thread_two starting/\n");
if(pthread_create(&th_two,null,(void*)&thread_two,msg)!=0)
sleep(3);
printf("thread_three starting/\n");
if(pthread_create(&th_three,null,(void*)&thread_three,msg)!=0)
exit(exit_failure);
pthread_join(th_one,null);
pthread_join(th_two,null);
pthread_join(th_three,null);
sleep(3);
printf("main thread will sleep 1 s\n");
return
0;
} static
void thread_two(char* msg)
,*p1,*p2;
//建立訊息佇列
msgid = msgget((key_t)1234, 0666 | ipc_creat);
if(msgid == -1)
//從佇列中獲取訊息,直到遇到end訊息為止
while(running)
printf("you wrote: %s\n",data.text);
//遇到end結束
if(strncmp(data.text, "end", 3) == 0)
break;
p1 = data.text;
p2 = a + strlen(data.text) - 1;
for( ; *p1 != '\0'; p1++, p2--)
*p2 = *p1;
*p2='\0';
printf("after reverse string a is: %s\n", a);
//向佇列傳送資料
data.msg_type = 1;
strcpy(data.text, a);
msgid = msgget((key_t)512, 0666 | ipc_creat);
if(msgid == -1)
if(msgsnd(msgid, (void*)&data, max_text, 0) == -1)
msgid=msgget((key_t)1234, 0666 | ipc_creat);
} //刪除訊息佇列
if(msgctl(msgid, ipc_rmid, 0) == -1)
exit(exit_success);
} static
void thread_one(char* msg)
//向訊息佇列中寫訊息,直到寫入end
while(running)
//輸入end結束輸入
if(strncmp(buffer, "end", 3) == 0)
running = 0;
sleep(1);
} exit(exit_success);
} static
void thread_three(char* msg)
;//建立訊息佇列
msgid = msgget((key_t)512, 0666 | ipc_creat);
if(msgid == -1)
//從佇列中獲取訊息,直到遇到end訊息為止
while(running)
printf("you reverse result: %s\n",data.text);
//遇到end結束
if(strncmp(data.text, "end", 3) == 0)
running = 0;
strcpy(a,data.text);
for(i=0;iif(a[i]>='a'&&a[i]<='z')
}printf("after upper string a is: %s\n", a);
//向佇列傳送資料
data.msg_type = 1;
strcpy(data.text, a);
msgid = msgget((key_t)1234, 0666 | ipc_creat);
if(msgsnd(msgid, (void*)&data, max_text, 0) == -1)
} //刪除訊息佇列
if(msgctl(msgid, ipc_rmid, 0) == -1)
exit(exit_success);
}
java多執行緒 訊息佇列
1 定義乙個佇列快取池 private static list queuecache new linkedlist 2 定義佇列緩衝池最大訊息數,如果達到該值,那麼佇列檢入將等待檢出低於該值時繼續進行。private integer offermaxqueue 2000 3 定義檢出執行緒,如果佇列...
利用多執行緒與訊息佇列實現聊天
在是乙個簡易聊天中提到,乙個程序只能做一件事,其實不然,只是當時沒有涉及到執行緒的概念。所以今天在用多執行緒來實現一次。依舊是兩個程式,每個程式包含兩個執行緒。include include include include include include include include includ...
linux C 多執行緒
標頭檔案 include 執行緒建立 pthread create 執行緒退出 pthread exit 互斥鎖 pthread mutex init pthread mutex lock pthread mutex unlock void thread function void arg if 0...