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;
}

posted @   repinkply  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示