linux下的c语言线程创建有关问题,求解阿
linux下的c语言线程创建问题,求解阿!
这是我的程序,执行后什么也没有。。。吾不解!
------解决方案--------------------
别让主线程退出太早~~
这是我的程序,执行后什么也没有。。。吾不解!
- C/C++ code
#include<stdio.h> #include<pthread.h> void *thread1(void) { int i=0; for(;i<10;i++) { printf("the 1st thread go %d\n",i); sleep(1); } } void *thread2(void) { int i=0; for(;i<10;i++) { printf("the 2st thread go %d\n",i); sleep(1); } } void main() { int a,b; pthread_create(&a,NULL,(void *)thread1,NULL); pthread_create(&b,NULL,(void *)thread2,NULL); }
------解决方案--------------------
别让主线程退出太早~~
- C/C++ code
int main() { pthread_t a,b; pthread_create(&a,NULL,(void *)thread1,NULL); pthread_create(&b,NULL,(void *)thread2,NULL); pthread_join(a,NULL); pthread_join(b,NULL); return 0; }
------解决方案--------------------
在 main 里面调用一下 pthread_exit(), 会结束 main 函数所在的线程,不影响另外的线程
- C/C++ code
void main() { int a,b; pthread_create(&a,NULL,(void *)thread1,NULL); pthread_create(&b,NULL,(void *)thread2,NULL); pthread_exit(NULL); }