簡體   English   中英

pthread如何創建許多線程

[英]pthread how to create many threads

要創建一個線程,我這樣做是這樣的:

void *routine(void *i){....}

pthread_t thread1;
pthread_create(&thread1, NULL, routine, NULL);

現在,我想創建100個線程,並且所有這些線程都執行routine ,是否必須執行以下操作? 是否可以使用for循環?

pthread_t thread1;
pthread_t thread2;
...
pthread_t thread100;

pthread_create(&thread1, NULL, routine, NULL);
pthread_create(&thread2, NULL, routine, NULL);
....
pthread_create(&thread100, NULL, routine, NULL);

您可以創建線程數組

#define NTHREADS 100
pthread_t th[NTHREADS];
int i;
for (i=0;i<NTHREADS;++i)
    pthread_create(&th[i],...);

只要拿pthread_t thread_arr[100]; (線程數組)。 在使用單個thread_t變量時進行計算。 使用pthread_arr [1],pthread_arr [2] ...作為單個變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM