linux线程创建和销毁

基本函数介绍

创建线程

int ptread_create(pthread_t *thread, 
    const pthread_att_t *attr,
    void * (*start)(void *),
    void *arg)
  • 返回值
  • 参数
    • thread
      pthread_t 类型的缓冲区,在创建函数返回前,会在此保存一个该线程的唯一标识。
    • attr
      线程属性,后续其他文章介绍,很多时候,直接用 NULL就能满足需求
    • start
      指向线程入口函数的指针,这个指针指向一个函数,这个函数的返回值时一个指针,参数也是一个指针。在应用线程取消技术的时候,不建议返回强制转换后的整型,因为取消线程的返回值 PTHREAD_CANCELED 一般也会时整型值,两个值有可能相同,可能会出现问题。
    • arg
      start函数的参数,一般指向一个全局或者堆变量,如果要传递多个参数,可以考虑把参数封装在一个结构体里面

终止线程

可以使用如下方式终止线程运行

  • start函数执行return语句并返回指定值
  • 线程调用 pthread_exit() 函数,和retrun不同地方是,在start函数所调用的任何函数中,调用 pthread_exit()都会终止线程
  • 调用pthread_cance()取消线程
  • 任何线程调用了exit()或者主线程执行了return语句,都会导致所有线程终止
void pthread_exit(void *retval)
  • retval
    线程的返回值,它所指向的内容不应该属于线程栈,因为线程返回之后,线程栈就销毁了

连接线程

对于未分离的线程,如果不执行 join,那么会形成僵尸线程

代码示例

#include "cstdio"
#include "pthread.h"
static void * thread_func(void *arg)
{
    int thread_name = *(int *)arg;
    pthread_t thread_id = pthread_self();
    printf ("[thread_name:%d][thread_id:%ld]\n",thread_name, (long)thread_id);
    return NULL;
}

int main()
{
    pthread_t thread_array[10];
    for (int i = 0;i < 10; i++)
    {
        int s = pthread_create(&thread_array[i], NULL, thread_func, &i);
        if (s != 0)
        {
            printf ("[create thread: %d error]\n", i);
            return -1;
        }
    }
    printf("[main thread]\n");
    for (int i = 0;i < 10; i++)
    {
        int s = pthread_join(thread_array[i], NULL);
        if (s != 0)
        {
            printf("[join thread: %d error]\n", i);
            return -1;
        }
    }
    return 0;
}
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值