Linux 多线程 pthread_create、pthread_join 、pthread_self

线程创建函数:

/* Create a new thread, starting with execution of START-ROUTINE
   getting passed ARG.  Creation attributed come from ATTR.  The new
   handle is stored in *NEWTHREAD.  */
extern int pthread_create (pthread_t *__restrict __newthread,
               const pthread_attr_t *__restrict __attr,
               void *(*__start_routine) (void *),
               void *__restrict __arg) __THROWNL __nonnull ((1, 3));

1. __newthread : pthread_t 变量的地址,用于返回线程标识,也就是线程id。

2.__attr : 线程的属性,可以设置为NULL,即:使用默认属性。

3.__start_routine : 线程入口函数

4.__arg : 线程入口函数的参数

/* Obtain the identifier of the current thread.  */
extern pthread_t pthread_self (void) __THROW __attribute__ ((__const__));

线程标识 :获取当前线程的 ID 标识

/* Make calling thread wait for termination of the thread TH.  The
   exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
   is not NULL.

   This function is a cancellation point and therefore not marked with
   __THROW.  */
extern int pthread_join (pthread_t __th, void **__thread_return);

线程等待 :等待目标线程执行结束

1.__th :目标线程 id

2. __thread_return : 目标线程的入口哈数的返回值。(也就是线程入口函数的返回值)。在大多数情况下:我们不需要这个返回值,这个返回值 为 NULL。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pthread.h>

void* thread_entry(void* arg)
{
    pthread_t id = pthread_self();
    int n =(long)arg;
    int i=0;

    for(i=0;i<n;i++)
    {
        printf("tid=%ld,i=%d\n",id,i);
        sleep(1);
    }

    return NULL;
}

void func2()
{
    pthread_t t1=0;
    pthread_t t2=0;
    int arg1=5;
    int arg2=5;

    pthread_create(&t1,NULL,thread_entry,(void*)arg1);
    pthread_create(&t2,NULL,thread_entry,(void*)arg2);

    printf("t1=%ld\n",t1);
    printf("t2=%ld\n",t2);

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);

    printf("child thead is finished...\n");
}

int main()
{

    func2();

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

repinkply

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值