UNIX環境進階編程:pthread_create的問題

來源:互聯網
上載者:User

linux 下常用的建立多線程函數pthread_create(pthread_t * thread , pthread_attr_t * attr , void *(*start_routine)(void*) , void *args);

其中第一個參數用來儲存線程資訊,第二個參數指新線程的運行屬性,可以設定為NULL,第三個參數為自訂的線程函數,第四個參數就是線程函數需要用到的參數,一般如果要傳遞多個參數,可以設定為結構體(struct)類型,這裡我們使用int類型的變數。  

下面我著重討論一個用for結構來建立多個線程時參數傳遞的問題:

#include <stdio.h>  #include <stdlib.h>  #include <pthread.h>              #define th_pop 20         pthread_mutex_t mutex;        pthread_t a_thread[th_pop];              void * thread_func(void *args)  {      pthread_mutex_lock(&mutex);      int t_id = *(int*)args;      printf("the id of this thread is %d\n",t_id);      pthread_mutex_unlock(&mutex);          return (void*)NULL;  }        void init()  {      pthread_mutex_init(&mutex, NULL);      int i;      for( i=0; i<th_pop; i++)      {          pthread_create(&a_thread[i] , NULL , thread_func , &i);      }      //wait the end of the threads;      for( i=0; i<th_pop; i++)      {          int res = pthread_join(a_thread[i] , NULL);          if(res != 0)              printf("the thread id: %d ends fail \n",i);      }      pthread_mutex_destroy(&mutex);            }        int main()  {      init();      return 0;  }

運行結果:

huangcheng@ubuntu:~$ ./a.outthe id of this thread is 2  the id of this thread is 8  the id of this thread is 9  the id of this thread is 9  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20  the id of this thread is 20

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.