您的位置:首页 > 其它

pthread 基础篇 结束线程

2013-05-21 20:18 134 查看
一 结束线程

1 当线程回调函数执行完后,即在回调函数中调用return语句时,默认线程终止(自然死亡)

2 显示调用pthread_exit函数(自尽^_^)。

3 调用exit函数,结束进程,也包括进程下的所有线程(地球消失了,自然活在地球上的人也就挂掉了^_^)

二 pthread_exit与return的区别

在主线程中(以main为回调函数的线程):

1· 在main中

调用return语句,会结束整个进程,即使进程下还有其他线程在工作。

调用pthread_exit,仅仅是结束main所在的线程,如果进程下还有其他线程在工作,则进程继续存在,其他线程正常工作。

2· 在一般线程中

在一般线程的回调函数中,调用return和pthread_exit效果是一样的。

当想要在回调函数调用的方法中结束线程时只能用pthread_exit。

三 测试代码

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

void *thread1_proc_function(void *argements)

{

int nCount = 0;

while(1)

{

printf("thread1 nCount = %d\n", nCount);

nCount++;

sleep(2);

if(3 == nCount)

{

pthread_exit(NULL);

}

}

}

void *thread2_proc_function(void *argements)

{

int nCount = 0;

while(1)

{

printf("thread2 nCount == %d\n", nCount);

nCount++;

sleep(2);

if(8 == nCount)

{

pthread_exit(NULL);

}

}

}

void thread_sub_function(void)

{

pthread_exit(NULL);

}

void *thread3_proc_function(void *argements)

{

int nCount = 0;

while(1)

{

printf("thread3 nCount == %d\n", nCount);

nCount++;

sleep(2);

if(15 == nCount)

{

thread_sub_function();

}

}

}

void main(void)

{

pthread_t thread1, thread2, thread3;

int iret1 = 0;

int iret2 = 0;

int iret3 = 0;

int nCount = 0;

iret1 = pthread_create(&thread1, NULL, thread1_proc_function, NULL);

iret2 = pthread_create(&thread2, NULL, thread2_proc_function, NULL);

iret3 = pthread_create(&thread3, NULL, thread3_proc_function, NULL);

while(1)

{

printf("main nCount = %d\n", nCount);

nCount ++;

sleep(2);

if(10 == nCount)

{

//return;

pthread_exit(NULL);

}

}

exit(0);

}

参考资料:

http://zh.wikipedia.org/wiki/Native_POSIX_Thread_Library

http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#BASICS
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: