Linux主線程接收資料,子執行緒分別對其操作後輸出

2021-07-12 01:39:12 字數 1298 閱讀 3491

本例子雖小,但是融合的執行緒同步,執行緒**和訊號量的知識。

需要注意pthread_join()和pthread_exit()的用法和區別:

pthread_join一般是主線程來呼叫,用來等待子執行緒退出,因為是等待,所以是阻塞的,一般主線程會依次join所有它建立的子執行緒。

pthread_exit一般是子執行緒呼叫,用來結束當前執行緒。

子執行緒可以通過pthread_exit傳遞乙個返回值,而主線程通過pthread_join獲得該返回值,從而判斷該子執行緒的退出是正常還是異常。

#include #include #include #include #include sem_t bin_sem;

int data;

void *thread_functionb(void *arg);

void *thread_functiona(void *arg);

int main(void)

res = pthread_create(&a_thread, null, thread_functiona, null);

if(res != 0)

res = pthread_create(&b_thread, null, thread_functionb, null);

if(res != 0)

//sem_wait(&bin_sem);

printf("input a number:\n");

scanf("%d",&data);

sem_post(&bin_sem);

if(pthread_join(a_thread, &thread_resulta)!=0)

if(pthread_join(b_thread, &thread_resultb)!=0)

printf("thread a has joined, it returned:%s\n", (char *)thread_resulta);

printf("thread b has joined, it returned:%s\n", (char *)thread_resultb);

printf("final data is:%d\n", data);

exit(exit_success);

}void *thread_functiona(void *arg)

void *thread_functionb(void *arg)

編譯並執行結果正確:

主線程和子執行緒

子執行緒通過 handlerthread的thread.getlooper 繫結,在主線程的handler的handlermessage中呼叫threadhandler.sendmessagedelay msg,1000 向子執行緒傳送訊息。在子執行緒中通過handler.sendmessagede...

主線程和子執行緒

主線程負責管理由它建立的子執行緒,建立 啟動 掛起 停止等。主線程通過發訊息的方式管理子執行緒,例如,給子執行緒傳送start 訊息,子執行緒啟動,子執行緒執行入口的run 方法。thread有下面兩個構造方法 thread runnable target,string name thread ru...

主線程獲得子執行緒中資料

場景 乙個執行緒繼續執行,需要另乙個執行緒執行完 public static void main string args catch interruptedexception e system.out.println 當前執行緒 thread.currentthread 結束 執行緒1 thread...