Linux操作系统下的多线程编程详细解析(2)

 

2、线程的终止

   
如果进程中任何一个线程中调用exit_Exit,或者是_exit,那么整个进程就会终止,
   
与此类似,如果信号的默认的动作是终止进程,那么,把该信号发送到线程会终止进程。
   
线程的正常退出的方式:
       (1)
线程只是从启动例程中返回,返回值是线程中的退出码
       (2)
线程可以被另一个进程进行终止
       (3)
线程自己调用pthread_exit函数
   
两个重要的函数原型:

#include <pthread.h>
void pthread_exit(void *rval_ptr);
/*rval_ptr
线程退出返回的指针*/

int pthread_join(pthread_t thread,void **rval_ptr);
   /*
成功结束进程为0,否则为错误编码*/


   
例程6
   
程序目的:线程正常退出,接受线程退出的返回码
   
程序名称:pthread_exit.c

/********************************************************************************************
**    Name:pthread_exit.c
**    Used to study the multithread programming in Linux OS
**    A example showing a thread to exit and with a return code.
**    Author:zeickey
**    Date:2006/9/16        
**    Copyright (c) 2006,All Rights Reserved!
*********************************************************************************************/

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

void *create(void *arg)
{
    printf("new thread is created ... /n");
    return (void *)8;
}

int main(int argc,char *argv[])
{
    pthread_t tid;
    int error;
    void *temp;

    error = pthread_create(&tid, NULL, create, NULL);

    if( error )
    {
        printf("thread is not created ... /n");
        return -1;
    }
    error = pthread_join(tid, &temp);

    if( error )
    {
        printf("thread is not exit ... /n");
        return -2;
    }
    
    printf("thread is exit code %d /n", (int )temp);
    return 0;
}

 
编译方法:

gcc -Wall pthread_exit.c -lpthread


   
执行结果:
new thread is created ...
thread is exit code 8

   
例程总结:
可以看出来,线程退出可以返回线程的int数值。线程退出不仅仅可以返回线程的int数值,还可以返回一个复杂的数据结构。

   
例程7
   
程序目的:线程结束返回一个复杂的数据结构
   
程序名称:pthread_return_struct.c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

struct menber
{
    int a;
    char *b;
}temp={8,"zieckey"};
void *create(void *arg)
{
    printf("new thread ... /n");
    return (void *)&temp;
}

int main(int argc,char *argv[])
{
    int error;
    pthread_t tid;
    struct menber *c;

    error = pthread_create(&tid, NULL, create, NULL);
   
    if( error )
    {
        printf("new thread is not created ... /n");
        return -1;
    }
    printf("main ... /n");

    error = pthread_join(tid,(void *)&c);

    if( error )
    {
        printf("new thread is not exit ... /n");
        return -2;
    }
    printf("c->a = %d  /n",c->a);
    printf("c->b = %s  /n",c->b);
    sleep(1);
    return 0;
}


 
编译方法:

gcc -Wall pthread_return_struct.c -lpthread


   
执行结果:

main ...
new thread ...
c->a = 8
c->b = zieckey


例程总结:
一定要记得返回的数据结构要是在这个数据要返回的结构没有释放的时候应用,
如果数据结构已经发生变化,那返回的就不会是我们所需要的,而是脏数据

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值