linux下的线程使用

函数简介

1:pthread_create是UNIX环境创建线程函数

头文件

#include<pthread.h>

函数声明

int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t restrict_attr,
void
start_rtn)(void),
void *restrict arg);

返回值

若成功则返回0,否则返回出错编号

参数

第一个参数为指向线程标识符的指针。

第二个参数用来设置线程属性。

第三个参数是线程运行函数的地址。

最后一个参数是运行函数的参数。

注意

在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库

2:pthread_join函数

函数简介

函数pthread_join用来等待一个线程的结束。

函数原型为:

extern int pthread_join __P (pthread_t __th, void **__thread_return);

参数:

第一个参数为被等待的线程标识符

第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。

注意

这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号

示例:

/*************************************************************************
    > File Name: pthread.c
    > Author: kayshi
    > Mail: kayshi2019@qq.com
    > Created Time: Mon 21 Sep 2020 03:12:09 PM CST
 ************************************************************************/

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

static void thread_fun1(void)
{
    while(1)
    {   
        printf("this is  thread1\n");
        sleep(1);
    }   
}

static void thread_fun2(void)
{
    while(1)
    {   
        printf("this is  thread2\n");
        sleep(1);
    }   
}

int main()
{
    pthread_t id1, id2;
    printf("start\n");
    pthread_create(&id1, NULL, (void *)thread_fun1, NULL);
    pthread_create(&id2, NULL, (void *)thread_fun2, NULL);
    pthread_join(id1, NULL);
    pthread_join(id2, NULL);
    printf("end\n");
}

编译执行

在这里插入图片描述


版权声明:本文为weixin_36209467原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。