#include <unistd.h> #include <stdio.h> #include <pthread.h> #include <stdlib.h> /*cpu个数,肯定进程数*/ #define cpunum 2 /*调试开关*/ #define debug 0 /*多个线程调用该函数*/ void *thrd_fun(void *data); struct THRD{ pid_t ppid; } thrddata; /*多个进程调用该函数*/ int callFuncation(int number); void main() { pid_t pid; int i; /*根据定义的cpu个数肯定fork进程数目*/ for(i=0;i<cpunum;i++) { pid=fork(); if(pid==0) { /*子进程调用函数*/ callFuncation(i); exit(-1); } else if(pid < 0) { fprintf(stdout,"fork error!\n"); exit(-1); } } wait(NULL); fprintf(stdout,"pid = [%d]\n",getpid()); exit(0); } int callFuncation(int number) { int thread_num=0; /*定义最大线程数*/ pthread_t thread[16]; fprintf(stdout,"fork number [%d] ppid = [%d]\n",number,getpid()); thrddata.ppid=getpid(); void *tret; for(thread_num=0;thread_num<5;thread_num++) { /*多个线程调用函数接口*/ if(pthread_create(&thread[thread_num],NULL,thrd_fun,(void *)&thrddata) !=0) { fprintf(stdout,"thread create error!\n"); return -1; } /*合并线程,确保所有线程执行完后,销毁线程,返回主函数*/ if (pthread_join(thread[thread_num],&tret)!=0) { fprintf(stdout, "Join thread %d error!\n",thread_num); return (-1); } else if(debug)fprintf(stdout, "Join thread %d success!\n",thread_num); } } /*线程函数*/ void *thrd_fun(void *data) { struct THRD *thdata; thdata=(struct THRD *)data; fprintf(stdout,"thd_data is [%d]!\n",thdata->ppid); pthread_exit(NULL); }
代码是N个月前写的,今天加的注释,若是有任何不妥之处,望不吝指出。
函数