pthread_create創建線程成功,但是沒有執行對應線程的函數怎麼回事

問題:

最近把以前的代碼又review了下,發現原來的多線程demo程序竟然沒得到如我預期的執行效果,即pthread_create創建線程成功,但是沒有執行對應線程的函數。後來發現是pthread的創建似乎會延遲一些時間,在pthread_create裏對應的線程函數運作之前,主程序(主線程)就已經結束了,當然看起來就像沒運作一樣。

解決方法:

在pthread_create後加一句sleep(1),讓主程序在此阻塞一秒

對比如下

線程一加了sleep(1),線程二未加sleep(1)

/*********************************************************************************
 *      Copyright:  (C) 2018 Wang Tao
 *                  All rights reserved.
 *
 *       Filename:  thread.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2018年05月15日)
 *         Author:  wang tao <[email protected]>
 *      ChangeLog:  1, Release initial version on "2018年05月15日 00時34分04秒"
 *                 
 ********************************************************************************/
#include <pthread.h>
#include <stdio.h>

/*線程一*/
void *thread_worker1(void *args)  //參數爲void *類型的函數可以接受任意一種類型的指針
{
  printf("thread worker1 [%lu] print %s\n\n",pthread_self(),(char *)args);   //pthread_self:獲取自己的線程ID
}

/* 線程二*/
void *thread_worker2(void *args)  
{                         
  printf("thread worker2 [%lu] print %s\n",pthread_self(),(char *)args);
}               

/********************************************************************************
 *  Description:
 *   Input Args:
 *  Output Args:
 * Return Value:
 ********************************************************************************/
int main (int argc, char **argv)   //寫多線程的程序,編譯時一定要鏈接線程的動態庫(gcc thread.c -lpthread )
{
    pthread_t   tid1;
    pthread_t   tid2;
    
    pthread_create(&tid1,NULL,thread_worker1,"cat");  //pthread_create:創建一個線程來執行一個函數
    printf("start thread_worker1 [%lu]\n",tid1);
    sleep(1);           ////////主線程在此阻塞一秒


    pthread_create(&tid2,NULL,thread_worker2,"dog");
    printf("start thread_worker2 [%lu]\n",tid2);

    return 0;
} /* ----- End of main() ----- */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章