#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define THREAD_NUM 4 void *threadfunc ( void *args) { printf("hello, I am the thread<%d>!/n",*((int *)args)); pthread_exit(NULL); } int main() { pthread_t tid[THREAD_NUM]; int td_index; int index; printf("Main program started!/n"); for( td_index = 0; td_index < THREAD_NUM; td_index++) { index =td_index; //Because the td_index maybe changed before passed into the threadfunc, //here we can't use it as the parameter passing into threadfunc. //if (pthread_create(&tid[td_index],NULL/*atti*/,threadfunc,(void *)&td_index/*args pass to threadfunc*/)) if (pthread_create(&tid[td_index],NULL/*atti*/,threadfunc,(void *)&index/*args pass to threadfunc*/)) { perror("create thread failed!/n"); exit -1; } } for( td_index = 0; td_index < THREAD_NUM; td_index++) { if (!pthread_equal(pthread_self(),tid[td_index])) //we can't join ourself { if(pthread_join(tid[td_index],NULL)) { perror("An error occured during join a thread!/n"); exit -1; } else printf("thread <%d> exit!/n",td_index); } else { perror("cant join myself!/n"); continue; } } exit(0); }
创建POSIX线程,向线程传递参数,收集线程
最新推荐文章于 2021-12-08 18:44:09 发布