在Linux中,线程是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。
基础概念:
相关优势:
类型:
应用场景:
问题与解决:
问题:线程间的同步和互斥问题,如数据竞争、死锁等。
解决:
示例代码(使用POSIX线程库pthread):
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void* print_hello(void* thread_id) {
long tid = (long)thread_id;
printf("Hello World! Thread ID, %ld\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t = 0; t < NUM_THREADS; t++) {
printf("In main: creating thread %ld
", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void*)t);
if (rc) {
printf("ERROR: return code from pthread_create() is %d
", rc);
exit(-1);
}
}
for(t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
pthread_exit(NULL);
}
在这个示例中,我们创建了5个线程,每个线程都执行print_hello
函数,打印出自己的线程ID。通过pthread_create
函数创建线程,通过pthread_join
函数等待线程结束。
领取专属 10元无门槛券
手把手带您无忧上云