在Linux环境下使用C语言进行多线程编程,通常会使用POSIX线程库(pthread)。下面是一个简单的多线程编程实例,包括创建线程、执行函数以及线程同步的基本概念。
下面是一个简单的C语言多线程编程示例,创建两个线程并打印信息:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
// 线程执行的函数
void* print_message(void* ptr) {
char* message = (char*) ptr;
printf("%s
", message);
return NULL;
}
int main() {
pthread_t thread1, thread2;
char* message1 = "Hello from Thread 1";
char* message2 = "Hello from Thread 2";
// 创建线程1
if (pthread_create(&thread1, NULL, print_message, (void*) message1)) {
fprintf(stderr, "Error creating thread 1
");
return 1;
}
// 创建线程2
if (pthread_create(&thread2, NULL, print_message, (void*) message2)) {
fprintf(stderr, "Error creating thread 2
");
return 1;
}
// 等待线程1结束
if (pthread_join(thread1, NULL)) {
fprintf(stderr, "Error joining thread 1
");
return 2;
}
// 等待线程2结束
if (pthread_join(thread2, NULL)) {
fprintf(stderr, "Error joining thread 2
");
return 2;
}
printf("All threads finished
");
return 0;
}
使用gcc编译器编译上述代码:
gcc -o multithread_example multithread_example.c -lpthread
运行编译后的程序:
./multithread_example
通过这个示例,你可以了解Linux下C语言多线程编程的基本流程和概念。在实际应用中,还需要考虑更多的线程管理和同步问题。
领取专属 10元无门槛券
手把手带您无忧上云