一个Linux下C线程池的实现(2)

void * myprocess (void *arg) {     printf ("threadid is 0x%x, working on task %d\n", pthread_self (),*(int *) arg);     sleep (1);/*休息一秒,延长任务的执行时间*/     return NULL; } int main (int argc, char **argv) {     pool_init (3);/*线程池中最多三个活动线程*/          /*连续向池中投入10个任务*/     int *workingnum = (int *) malloc (sizeof (int) * 10);     int i;     for (i = 0; i < 10; i++)     {         workingnum[i] = i;         pool_add_worker (myprocess, &workingnum[i]);     }     /*等待所有任务完成*/     sleep (5);     /*销毁线程池*/     pool_destroy ();     free (workingnum);     return 0; }

将上述所有代码放入threadpool.c文件中,
Linux输入编译命令
$ gcc -o threadpool threadpool.c -lpthread

以下是运行结果
starting thread 0xb7df6b90
thread 0xb7df6b90 is waiting
starting thread 0xb75f5b90
thread 0xb75f5b90 is waiting
starting thread 0xb6df4b90
thread 0xb6df4b90 is waiting
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 0
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 1
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 2
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 3
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 4
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 5
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 6
thread 0xb75f5b90 is starting to work
threadid is 0xb75f5b90, working on task 7
thread 0xb6df4b90 is starting to work
threadid is 0xb6df4b90, working on task 8
thread 0xb7df6b90 is starting to work
threadid is 0xb7df6b90, working on task 9
thread 0xb75f5b90 is waiting
thread 0xb6df4b90 is waiting
thread 0xb7df6b90 is waiting
thread 0xb75f5b90 will exit
thread 0xb6df4b90 will exit
thread 0xb7df6b90 will exit

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwxdfz.html