pthread如何创建多个线程

时间:2015-03-16 16:26:04

标签: c++ multithreading pthreads

要创建一个线程,我确实喜欢这个:

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);

2 个答案:

答案 0 :(得分:3)

您可以创建一个线程数组

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

答案 1 :(得分:1)

只需要pthread_t thread_arr[100];(线程数组)。在使用单个thread_t变量时进行处理。使用pthread_arr [1],pthread_arr [2] ...作为单个变量。