执行结果: main ... new thread ... c->a = 8 c->b = zieckey 例程总结: 一定要记得返回的数据结构要是在这个数据要返回的结构没有释放的时候应用,如果数据结构已经发生变化,那返回的就不会是我们所需要的,而是脏数据。
#include <pthread.h> int pthread_join(pthread_t thread, void **rval_ptr); pthread_join用于挂起当前线程(调用pthread_join的线程),直到thread指定的线程终止运行为止,当前线程才继续执行。thread指定的线程的返回值由rval_ptr返回。一个线程所使用的资源在对该线程调用pthread_join之前不会被重新分配,因此对于每个切入的线程必须调用一次pthread_join函数。线程必须可切入的而不是处于被分离状态,并且其他线程不能对同一线程再次应用pthread_join调用。通过pthread_create调用中使用一个适当的attr参数或者调用pthread_detach可以让一个线程处于被分离状态。
#include<pthread.h> #include<unistd.h> #include<stdio.h> void*thread(void*str) { int i; for(i = 0; i < 10;++i) { sleep(2); printf("This in the thread : %d\n", i ); } returnNULL; }
int main() { pthread_t pth; int i; int ret =pthread_create(&pth,NULL, thread,(void*)(i)); pthread_join(pth,NULL); for(i = 0; i < 10;++i) { sleep(1); printf("This in the main : %d\n", i ); } return 0; }
"pthread_join(pth, NULL);"这一行注释掉: [root@localhost src]# gcc pthread_join.c -lpthread [root@localhost src]#./a.out Thisin the main : 0 Thisin the thread : 0 Thisin the main : 1 Thisin the main : 2 Thisin the thread : 1 Thisin the main : 3 Thisin the main : 4 Thisin the thread : 2 Thisin the main : 5 Thisin the main : 6 Thisin the thread : 3 Thisin the main : 7 Thisin the main : 8 Thisin the thread : 4 Thisin the main : 9
子线程还没有执行完毕,main函数已经退出,那么子线程也就退出了。
“pthread_join(pth, NULL);”起作用 [root@localhost src]# gcc pthread_join.c -lpthread [root@localhost src]#./a.out Thisin the thread : 0 Thisin the thread : 1 Thisin the thread : 2 Thisin the thread : 3 Thisin the thread : 4 Thisin the thread : 5 Thisin the thread : 6 Thisin the thread : 7 Thisin the thread : 8 Thisin the thread : 9 Thisin the main : 0 Thisin the main : 1 Thisin the main : 2 Thisin the main : 3 Thisin the main : 4 Thisin the main : 5 Thisin the main : 6 Thisin the main : 7 Thisin the main : 8 Thisin the main : 9 [root@localhost src]#