在Linux下,线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
基础概念:
相关优势:
类型:
应用场景:
常见问题及解决方法:
示例代码(使用POSIX线程库pthread在Linux下创建线程):
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void* thread_func(void* arg) {
printf("Hello from thread %ld
", (long)arg);
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);
exit(-1);
}
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads have finished.
");
return 0;
}
这段代码创建了5个线程,每个线程打印一条消息。主线程等待所有子线程完成后退出。
领取专属 10元无门槛券
手把手带您无忧上云