關於子線程執行兩次的問題

來源:互聯網
上載者:User

標籤:self   意義   緩衝區   實現   write   turn   argc   sign   情境   

#include<pthread.h>#include<stdio.h>pthread_t ntid;void printids(const char *s){    pid_t pid;    pthread_t tid;    pid = getpid();    tid = pthread_self();    printf("%s pid %lu tid %lu (0x%lx)\n",s,(unsigned long)pid,            (unsigned long)tid,(unsigned long)tid);}void * thr_fn(void *arg)                                                                                                                   {    printids("new thread:");    return ((void *)0);}int main(int argc, const char *argv[]){    int err;    err = pthread_create(&ntid,NULL,thr_fn,NULL);    if(err !=0)    {        perror("erro");       return 0;    }    printids("main thread:");//  sleep(1);    return 0;}

  在運行時會出現3中情況:

1.

main thread: pid 4815 tid 3075843776 (0xb755a6c0)new thread: pid 4815 tid 3075840832 (0xb7559b40)

2.

main thread: pid 4800 tid 3076433600 (0xb75ea6c0)

3.

main thread: pid 4773 tid 3075663552 (0xb752e6c0)new thread: pid 4773 tid 3075660608 (0xb752db40)new thread: pid 4773 tid 3075660608 (0xb752db40)

第一種情況可以理解為:主線程先運行,正要退出的時候,子線程運行了

第二種情況可以理解為:主線程運行完了,並結束了進程,這時子線程還沒來的及運行。

第三種情況理解:答案是從網上找到的:https://segmentfault.com/q/1010000003739810?sort=created

首先,這個程式是錯誤的,在exit()的時候會在stdout上發生競爭。
  你要明白,發生競爭之後出現什麼情況都不稀奇,所以不要深究這個原因了,沒有意義,這跟stdio的實現相關。

  舉個可能的情境滿足你的好奇心,比如:
  新線程的printf在寫完緩衝區之後執行flush——調用write,再要把已經write過的資料從緩衝區中刪掉,但是在刪除之前,main線程的exit也要flush stdout,就可能把已經flush過          的資料又flush了一遍。

 

關於子線程執行兩次的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.