在Linux中,线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
基础概念:
相关优势:
类型:
在Linux中,线程主要分为用户级线程和内核级线程。用户级线程由用户空间的线程库管理,内核级线程由操作系统内核管理。Linux系统主要采用内核级线程,即通常所说的轻量级进程。
应用场景:
遇到的问题及解决方法:
示例代码(使用POSIX线程库pthread创建线程):
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_func(void* arg) {
printf("Hello from thread %ld
", (long)arg);
sleep(1); // 模拟耗时操作
return NULL;
}
int main() {
pthread_t threads[5];
int rc;
for (long t = 0; t < 5; t++) {
rc = pthread_create(&threads[t], NULL, thread_func, (void*)t);
if (rc) {
printf("Error: unable to create thread %d
", rc);
return -1;
}
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL); // 等待线程结束
}
printf("All threads have finished.
");
return 0;
}
在这个示例中,我们创建了5个线程,每个线程都会打印一条消息并休眠1秒。主线程会等待所有子线程结束后再继续执行。
领取专属 10元无门槛券
手把手带您无忧上云