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、线程中没有父子关系,只有主进程和其他线程之分