8、操作系统——线程(最小的执行单位)

目录

一、线程(应用层)的理解

二、编译的时候需要手动链接线程库POSIX

三、创建一个线程

1、API

pthread_create(创建线程)

2、创建一个线程,输出主函数和线程的id

四、知识点

一、线程(应用层)的理解

在linux内核中,所有的调度实体都被称为任务

区别:

(1)有些任务自己拥有一套完整的资源

(2)有些任务彼此之间共享一套资源

二、编译的时候需要手动链接线程库POSIX

$ gcc pthread.c -o pthread -lpthread

三、创建一个线程

1、API

pthread_create(创建线程)

特点:
(1)线程创建成功,线程会立即去执行函数

(2)POSIX线程库的所有API,成功返回0,失败返回错误码errno

(3)线程属性如果为NULL,则会创建一个标准属性的线程

2、创建一个线程,输出主函数和线程的id

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

void * func (void * arg)
{
    while(1)
    {
        printf("这里是func线程,线程ID :%ld \n" , pthread_self() );
        sleep(1);
    }
}

int main(int argc, char const *argv[])
{
    
    // 创建线程
    pthread_t t_id  = -1 ;  
    pthread_create( &t_id , //新线程ID号
                    NULL , // 线程属性, NULL 默认属性
                    func,  // 线程需要执行的例程(新线程需要执行的任务《函数》) 
                    NULL ); // 线程的参数

    printf("t_id : %ld\n" , t_id) ;
    while(1)
    {
        printf("这里是主函数,线程ID :%ld \n" , pthread_self() );
        sleep(1);
    }

    return 0;
}

四、知识点

1、pthread_self()返回线程的id

2、在线程中,出现错误一般都是返回错误号码(告知是哪个线程出错)

3、线程中没有父子关系,只有主进程和其他线程之分

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值