线程的创建与退出

头文件   #include <pthread.h>

线程的创建   pthread_create()

线程的退出   pthread_exit()

等待线程的退出  pthread_join()

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void thread()
{
        printf("This is child thread!\n");
        return ;
}

int main()
{
        pthread_t id;  
        int ret;
        ret = pthread_create(&id, NULL, (void *)thread, NULL); //创建线程(第一个参数是线程号;第二个参数为线程属性,一般置为NULL;
                                                        //第三个参数为线程要调用的函数的首地址;第四个参数为传递给线程函数的参数)
        if(ret != 0)
        {
                perror("pthread_create.");
                exit(1);
        }

        printf("This is main thread!\n");
        pthread_join(id, NULL);   //等待线程结束
        printf("Child thread return.\n");

        return 0;
}
执行结果:

This is main thread!
This is child thread!
Child thread return.


#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <pthread.h>

void* thread(int num)
{
        printf("This is chlid thread!\n");
        num *= 2;
        //return (void *)num;
        pthread_exit((void *)10);
}

int main()
{
        pthread_t id;
        int ret;
        void *result;

        ret = pthread_create(&id, NULL, (void *)thread, (void *)5);
        if(ret != 0)
        {
                perror("pthread_create");
                exit(1);
        }

        printf("This is main thread!\n");

        pthread_join(id, &result);   //第二个参数为void ** 型,用来取得线程退出信息。
        printf("Child thread return %d.\n",(int)result);

        return 0;
}

执行结果:

This is main thread!
This is chlid thread!
Child thread return 10.


关于return 与 pthread_exit(void *)的区别:

对于线程函数来说,调用return和pthread_exit()都将使该线程返回。但return所做的是函数返回(在线程结束的时候会自动调用pthread_exit()来释放线程所占用的资源,包括主线程),而phtread_exit()则显式的释放空间并设置了返回值。pthread_exit()属于线程退出函数,但renturn不是。

两者都会将退出的值放到pthread_join(id, void **)中的第二个参数所指向的地址里,主线程也就获得了子线程返回的信息。



关于线程的操作还有一些函数:

int pthread_detach(pthread_t tid)   //使该线程从进程中分离(分离后线程会自动释放资源)

int pthread_cancel(pthread_t tid)   //用来取消一个线程


void pthread_cleanup_push(void (*rtn)(void *), void *arg);   //用来设置线程的清理程序

void pthread_cleanup_pop(int execute);

(以上两个函数必须成对出现)

更多信息参考:

http://www.ibm.com/developerworks/cn/linux/thread/posix_threadapi/part4/

http://blog.chinaunix.net/uid-23193900-id-3193923.html



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值