在Linux下使用GCC进行多线程编程,通常涉及以下几个步骤:
包含头文件:
#include <pthread.h>:这是POSIX线程库的头文件,提供了创建和管理线程所需的函数和数据类型。定义线程函数:
void* thread_function(void* arg);
arg 是传递给线程函数的参数。创建线程:
pthread_create 函数创建线程:pthread_t thread_id;
int result = pthread_create(&thread_id, NULL, thread_function, (void*)arg);
if (result != 0) {
// 处理错误
}
thread_id 是一个 pthread_t 类型的变量,用于存储线程的标识符。NULL 表示使用默认的线程属性。thread_function 是线程函数的指针。(void*)arg 是传递给线程函数的参数。等待线程结束:
pthread_join 函数等待线程结束:void* result;
int status = pthread_join(thread_id, &result);
if (status != 0) {
// 处理错误
}
thread_id 是要等待的线程的标识符。&result 是一个指向 void* 的指针,用于接收线程函数的返回值。销毁线程:
pthread_exit 函数显式地结束线程:pthread_exit(NULL);
编译和链接:
-pthread:gcc -o my_program my_program.c -pthread
下面是一个简单的多线程示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_function(void* arg) {
int thread_num = *(int*)arg;
printf("Thread %d is running\n", thread_num);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int thread_args[5];
for (int i = 0; i < 5; i++) {
thread_args[i] = i;
int result = pthread_create(&threads[i], NULL, thread_function, (void*)&thread_args[i]);
if (result != 0) {
fprintf(stderr, "Error creating thread %d\n", i);
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < 5; i++) {
void* result;
int status = pthread_join(threads[i], &result);
if (status != 0) {
fprintf(stderr, "Error joining thread %d\n", i);
exit(EXIT_FAILURE);
}
}
printf("All threads have finished\n");
return 0;
}
编译并运行这个程序:
gcc -o my_program my_program.c -pthread
./my_program
这个程序创建了5个线程,每个线程打印自己的编号,然后主线程等待所有子线程结束后退出。