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]... 作为独立变量。
为了创建一个线程,我是这样做的:
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]... 作为独立变量。