多线程(一):生成多个线程

来源:互联网 发布:把男朋友撩硬不管知乎 编辑:程序博客网 时间:2024/04/29 14:56

其实只在前一篇文章的基础上改了少许代码

#include <stdio.h>#include <pthread.h>#define THREADNUM 3void thread(int i) {printf("This is thread:%d\n", i);pthread_exit(NULL);}int main(void) {pthread_t id[THREADNUM];int ret, i;for(i=0; i<THREADNUM; i++) {ret = pthread_create(&id[i], NULL, (void *)thread, i);if(ret != 0) {printf("Create thread error!\n");exit(1);}}for(i=0; i<THREADNUM; i++) {pthread_join(id[i], NULL);}printf("This is the main process.\n");return 0;}

这次的代码给thread函数传递了一个参数,而这个参数是通过pthread_create函数的第四个参数传过去的。

顺便提一句,pthread_create中的第三个参数,使用(void *)thread或者是(void *)&thread都对。(可能只是暂时都对,这个问题先放一边)

需要注意的是,pthread_join要另外写一个for循环,如果把这个函数与第一个for循环放到一起的话,从速度或是什么其他角度看上去,感觉不能算是多线程,三个线程还是顺序执行的。

执行此代码,会发现打印出的三个线程的顺序是随机的(不一定是0 1 2的顺序),创建多个线程成功~