本文旨在为读者提供Linux环境下多线程编程的详细入门指南。尽管定位为入门教程,内容涵盖核心概念与关键API的使用,帮助读者建立对Linux多线程编程体系的清晰认知。具体内容包括线程基础、标识、创建、终止及生命周期管理等章节。
1 线程基本知识
在操作系统中,进程被视为资源分配与管理的基本单位,而线程则是CPU调度的基本单位。线程是操作系统能够执行运算的最小实体,它存在于进程内部,是进程中实际执行任务的工作单元。一条线程代表进程中一个单一顺序的控制流,一个进程内部可以并发运行多个线程,每条线程独立并行地执行不同的任务逻辑。
在没有多线程支持的情况下,一个进程在同一时刻只能执行单一任务。引入多线程后,程序设计可以在同一时间点处理多项事务,每个线程负责独立的任务处理,从而提升程序的并发处理能力。
值得注意的是,即使程序运行在单核处理器上,采用多线程编程模型依然能带来益处。处理器的物理数量并不决定程序结构的优劣,无论处理器核心数多少,通过线程划分任务都可以简化程序逻辑并优化执行流程。
Linux操作系统采用符合POSIX标准的线程实现作为系统标准线程。该POSIX线程标准定义了一套完整的API,用于规范线程的各种操作行为。
2. 线程标识
类似于进程拥有唯一的进程ID(PID),每个线程也拥有自己的线程ID。两者的区别在于,进程ID在整个系统中是全局唯一的,而线程ID仅在其所属的进程范围内有效,因为线程依附于进程存在。在线程编程中,线程ID的数据类型定义为pthread_t。
//pthread_self直接返回调用线程的ID
include
pthread_t pthread_self(void);
判断两个线程ID的大小关系没有实际意义,但在某些场景下需要判断两个给定的线程ID是否指向同一个线程。为此,可以使用特定的接口进行相等性比较。
//pthread_equal如果t1和t2所指定的线程ID相同,返回0;否则返回非0值。
include
int pthread_equal(pthread_t t1, pthread_t t2);
3. 线程创建
线程的生命周期始于其被创建的时刻。在Linux中,创建新线程主要依赖特定的接口函数。
#include
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
函数参数说明如下:
thread(输出参数),由pthread_create在线程创建成功后返回的线程句柄,该句柄在后续操作线程的API中用于标志该新建的线程;
start_routine(输入参数),新建线程的入口函数;
arg(输入参数),传递给新线程入口函数的参数;
attr(输入参数),指定新建线程的属性,如线程栈大小等;如果值为NULL,表示使用系统默认属性。
函数返回值情况如下:
成功,返回0;
失败,返回相关错误码。
在使用线程创建接口时,需要注意以下几点:
1.主线程,这是一个进程的初始线程,其入口函数为main函数。 2.新线程的运行时机,一个线程被创建之后有可能不会被马上执行,甚至,在创建它的线程结束后还没被执行;也有可能新线程在当前线程从pthread_create前就已经在运行,甚至,在pthread_create前从当前线程返回前新线程就已经执行完毕。
以下是一个具体的程序实例,展示线程的创建与运行。
#include
#include
#include
#include
void printids(const char *s){
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s, pid %lu tid %lu (0x%lx)\n",s,(unsigned long)pid,(unsigned long)tid,
(unsigned long)tid);
}
void *thread_func(void *arg){
printids("new thread: ");
return ((void*)0);
}
int main() {
int err;
pthread_t tid;
err = pthread_create(&tid,NULL,thread_func,NULL);
if (err != 0) {
fprintf(stderr,"create thread fail.\n");
exit(-1);
}
printids("main thread:");
sleep(1);
return 0;
}
在上述程序中,主线程休眠一秒。如果不设置休眠,主线程可能会迅速退出,导致新创建的子线程来不及执行就被终止。在实际测试中,若注释掉sleep函数,往往需要多次运行才能观察到新线程的输出结果。
编译该程序需要使用以下命令:
gcc -o thread thread.c -lpthread
运行上述程序后的结果如下所示:
main thread:, pid 889 tid 139846854309696 (0x7f30a212f740)
new thread: , pid 889 tid 139846845961984 (0x7f30a1939700)
从运行结果可以看出,主线程与新线程的进程ID(pid)是相同的。这证实了线程共享其所属进程的资源。
4. 线程终止
线程的终止主要分为两种形式:被动终止和主动终止。
被动终止包含以下两种方式:
1.线程所在进程终止,任意线程执行exit、_Exit或者_exit函数,都会导致进程终止,从而导致依附于该进程的所有线程终止。 2.其他线程调用pthread_cancel请求取消该线程。
主动终止也有两种方式:
1.在线程的入口函数中执行return语句,main函数(主线程入口函数)执行return语句会导致进程终止,从而导致依附于该进程的所有线程终止。 2.线程调用pthread_exit函数,main函数(主线程入口函数)调用pthread_exit函数, 主线程终止,但如果该进程内还有其他线程存在,进程会继续存在,进程内其他线程继续运行。
线程终止相关的函数接口如下:
include
void pthread_exit(void *retval);
线程调用pthread_exit函数会导致该调用线程终止,并且返回由retval指定的内容。需要注意的是,retval指针不能指向该线程自身的栈空间,否则可能导致野指针问题,引发未定义行为。
5. 管理线程的终止
5.1 线程的连接
对于其他线程而言,一个线程的终止是一种异步事件。有时我们需要等待特定ID的线程终止后再执行后续操作,pthread_join函数提供了这种同步机制,该功能被称为线程的连接。
include
int pthread_join(pthread_t thread, void **retval);
参数说明如下:
thread(输入参数),指定我们希望等待的线程
retval(输出参数),我们等待的线程终止时的返回值,就是在线程入口函数中return的值或者调用pthread_exit函数的参数
返回值情况如下:
成功时,返回0
错误时,返回正数错误码
当线程X连接线程Y时,如果线程Y仍在运行,则线程X会阻塞,直到线程Y终止;如果线程Y在被连接之前已经终止,那么线程X的连接调用会立即返回。
连接线程还具有另一层重要意义:一个线程终止后,如果没有其他线程对其进行连接,系统将无法回收该终止线程所占用的资源,该线程将变成僵尸线程。因此,执行连接操作也是在通知系统可以回收该线程的资源了。
注意:对于一个已经被连接过的线程再次执行连接操作,将会导致无法预知的行为!
5.2 线程的分离
有时我们并不关心某个线程是否已经终止,只希望在线程终止后,系统能自动回收其占用的资源。pthread_detach函数提供了这一功能,称为线程的分离。
#include
int pthread_detach(pthread_t thread);
默认情况下,线程终止后需要被连接,系统才会回收其资源。如果调用pthread_detach函数分离某个线程,则该线程终止后,系统将自动回收其资源,无需显式连接。
/*
* 文件名: thread_sample1.c
* 描述:演示线程基本操作
*/
#include
#include
#include
#include
/*子线程1入口函数*/
void *thread_routine1(void *arg)
{
fprintf(stdout, "thread1: hello world!\n");
sleep(1);
/*子线程1在此退出*/
return NULL;
}
/*子线程2入口函数*/
void *thread_routine2(void *arg)
{
fprintf(stdout, "thread2: I'm running...\n");
pthread_t main_thread = (pthread_t)arg;
/*分离自我,不能再被连接*/
pthread_detach(pthread_self());
/*判断主线程ID与子线程2ID是否相等*/
if (!pthread_equal(main_thread, pthread_self())) {
fprintf(stdout, "thread2: main thread id is not equal thread2\n");
}
/*等待主线程终止*/
pthread_join(main_thread, NULL);
fprintf(stdout, "thread2: main thread exit!\n");
fprintf(stdout, "thread2: exit!\n");
fprintf(stdout, "thread2: process exit!\n");
/*子线程2在此终止,进程退出*/
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
/*创建子线程1*/
pthread_t t1;
if (pthread_create(&t1, NULL, thread_routine1, NULL)!=0) {
fprintf(stderr, "create thread fail.\n");
exit(-1);
}
/*等待子线程1终止*/
pthread_join(t1, NULL);
fprintf(stdout, "main thread: thread1 terminated!\n\n");
/*创建子线程2,并将主线程ID传递给子线程2*/
pthread_t t2;
if (pthread_create(&t2, NULL, thread_routine2, (void *)pthread_self())!=0) {
fprintf(stderr, "create thread fail.\n");
exit(-1);
}
fprintf(stdout, "main thread: sleeping...\n");
sleep(3);
/*主线程使用pthread_exit函数终止,进程继续存在*/
fprintf(stdout, "main thread: exit!\n");
pthread_exit(NULL);
fprintf(stdout, "main thread: never reach here!\n");
return 0;
}
最终的执行结果如下:
thread1: hello world!
main thread: thread1 terminated!
main thread: sleeping...
thread2: I'm running...
thread2: main thread id is not equal thread2
main thread: exit!
thread2: main thread exit!
thread2: exit!
thread2: process exit!
总结
以上就是本文关于Linux多线程编程快速入门的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!