ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Linux用户态线程pthread简单应用

2020-10-22 14:01:34  阅读:246  来源: 互联网

标签:join 函数 Linux exit pthread 线程 ptr


1、pthread_exit函数

void pthread_exit( void * value_ptr );
线程的终止可以是调用pthread_exit手动结束或者该线程的例程运行完成自动结束。
也就是说,一个线程可以隐式的退出,也可以显式的调用pthread_exit函数来退出。 pthread_exit函数唯一的参数value_ptr是函数的返回代码,只要pthread_join中的第二个参数value_ptr不是NULL,这个值将被传递给value_ptr。
使用函数pthread_exit退出线程,这是线程的主动行为;
由于一个进程中的多个线程是共享数据段的,因此通常在线程退出之后,退出线程所占用的资源并不会随着线程的终止而得到释放,
但是可以用pthread_join()函数来同步并释放资源。 
retval:pthread_exit()调用线程的返回值,可由其他函数如pthread_join来检索获取。

2、pthread_join函数

int pthread_join( pthread_t thread, void * * value_ptr ); 函数pthread_join的作用是,等待一个线程终止。 
调用pthread_join的线程,将被挂起,直到参数thread所代表的线程终止时为止。
pthread_join是一个线程阻塞函数,调用它的函数将一直等到被等待的线程结束为止。 如果value_ptr不为NULL,那么线程thread的返回值存储在该指针指向的位置。
该返回值可以是由pthread_exit给出的值,或者该线程被取消而返回PTHREAD_CANCELED。
3、pthread_exit函数在main函数中的用法





例子:
/*thread.c*/
#include <stdio.h>
#include <pthread.h>
 
/*线程一*/
void thread_1(void)
{
    int i=0;
    for(i=0;i<=1000;i++)
    {
        printf("This is a pthread1.\n");
        if(i==500)
            pthread_exit(0);//用pthread_exit()来调用线程的返回值,用来退出线程,但是退出线程所占用的资源不会随着线程的终止而得到释放
        sleep(1);
    }
}
 
/*线程二*/
void thread_2(void)
{
    int i;
    for(i=0;i<300;i++)
        printf("This is a pthread2.\n");         
    pthread_exit(0);//用pthread_exit()来调用线程的返回值,用来退出线程,但是退出线程所占用的资源不会随着线程的终止而得到释放
}
 
int main(void)
{
    pthread_t id_1,id_2;
    int i,ret;
/*创建线程一*/
    ret=pthread_create(&id_1,NULL,(void  *) thread_1,NULL);
    if(ret!=0)
    {
        printf("Create pthread1 error!\n");
    return -1;
    }
/*创建线程二*/
    ret=pthread_create(&id_2,NULL,(void  *) thread_2,NULL);
    if(ret!=0)
    {
        printf("Create pthread2 error!\n");
    return -1;
    }
/*等待线程结束*/
    pthread_join(id_1,NULL);
    pthread_join(id_2,NULL);
    return 0;
}

备注:pthread库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以在线程函数在编译时,需要连接库函数。
makefile添加:gcc create.c -o pthreadapp -lpthread


参考引用:
https://blog.csdn.net/youbang321/article/details/7816016#

标签:join,函数,Linux,exit,pthread,线程,ptr
来源: https://www.cnblogs.com/ggzhangxiaochao/p/13857865.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有