在Linux下,线程库主要指的是POSIX线程库,也称为pthread库。以下是对pthread库的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方案的详细解释:
以下是一个简单的pthread程序示例,创建两个线程并打印信息:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_func(void* arg) {
int id = *(int*)arg;
printf("Thread %d is running
", id);
sleep(1); // 模拟耗时操作
printf("Thread %d is exiting
", id);
return NULL;
}
int main() {
pthread_t thread1, thread2;
int id1 = 1, id2 = 2;
// 创建线程1
if (pthread_create(&thread1, NULL, thread_func, &id1) != 0) {
perror("pthread_create");
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, thread_func, &id2) != 0) {
perror("pthread_create");
return 1;
}
// 等待线程结束
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("All threads are done
");
return 0;
}
编译并运行该程序,可以看到两个线程并发执行并打印信息。
领取专属 10元无门槛券
手把手带您无忧上云