在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個線程,每個線程打印自己的編號,然后主線程等待所有子線程結束后退出。