linux 线程

Linux 线程

1.线程概念:一个进程内部的一个控制序列

2.特点:一个进程在同一时刻只做一件事情。有了多个控制线程以后,在程序设计时可以把进程设计成在同一时刻能够做不止一件事,每个线程处理各只独立的任务。

3.线程的标识:线程ID用pthread_t数据类型来表示,实现的时候可以用一个结构来代表pthread_t数据类型,所以可以移植的操作系统不能把它作为整数处理。

4.线程的创建:pthread_create

简介:头文件 #include<pthread.h>

函数原型:int pthread_create(pthread_t *restrict tidp,const pthread _attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg);

返回值:若成功返回0,失败返回错误编码

过程: 当pthread_creat成功返回时, tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于定制各种不同的线程属性。可以把它设置为NULL,创建默认的线程属性。

 新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。

编译过程(注意):关于进程的编译我们都要加上参数 –lpthread 否则提示找不到函数的错误。

5.线程的终止

函数:pthread_join获得进程的终止状态

头文件: #include<pthread.h>

函数原型:int pthread_join(pthread_t thread,void **rval_ptr);

返回值:成功返回0,失败返回错误编号

代码演示线程的创建和退出:

  1 #include<pthread.h>

  2 #include<stdio.h>

  3

  4 void* pthread_fun(void *arg)

  5 {   

  6     printf("create a pthread!\n");

  7 }

  8 int main()

  9 {   

 10     pthread_t tid;

 11     pthread_create(&tid,NULL,pthread_fun,NULL);

 12     

 13     

 14     pthread_join(tid,NULL);

 15     return 0;

 16 }

结果:create a pthread!

 

 

 

 

 

Linux系统中,从操作系统视角来看,没有真正意义的线程,而是用进程模拟线程(LWP,轻量级进程),Linux不会提供直接创建线程的系统调用,最多提供创建轻量级进程的接口。不过,为满足用户对线程接口的需求,Linux提供了用户线程库,即pthread库(原生线程库),它对下封装Linux接口,对上为用户提供线程控制接口 [^2]。 Linux系统中线程的相关操作通常涉及创建、同步、互斥、通信、终止以及获取线程信息等,这些操作一般通过POSIX线程pthread)库实现 [^1]。 ### 线程创建 使用`pthread_create()`函数可在当前进程中创建一个新线程,并将其与指定函数关联起来。以下是一个简单示例: ```c #include <pthread.h> #include <stdio.h> // 线程执行的函数 void* thread_function(void* arg) { printf("This is a new thread.\n"); return NULL; } int main() { pthread_t thread_id; // 创建线程 int result = pthread_create(&thread_id, NULL, thread_function, NULL); if (result != 0) { perror("pthread_create"); return 1; } // 等待线程结束 pthread_join(thread_id, NULL); return 0; } ``` ### 线程回收 默认情况下,新创建的线程是不分离的,线程退出后,同组的其它线程需要对其进行`pthread_join`等待操作,否则无法释放资源,从而导致系统资源泄漏。若不关心线程返回值,可让线程分离,即告诉系统,当线程终止时,操作系统可直接回收该线程资源 [^4]。 ### 线程原理 线程由`task_struct`模拟,对于Linux操作系统而言,实际上不存在线程概念,只认识`task_struct`,线程是从用户角度的理解。因此,Linux操作系统的系统调用接口不会提供直接创建、调度、销毁线程的接口,仅提供操作`task_struct`的相关接口。为降低开发难度,Linux系统程序员在用户层面封装了一套接口,即`#include <pthread.h>`中的`pthread_create`、`pthread_exit`等 [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值