在Ubuntu下使用GCC編譯多線程程序,你需要使用-pthread
選項。這是一個示例:
multithread_example.c
的源文件,內容如下:#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_hello(void *ptr) {
int thread_id = *(int *)ptr;
printf("Hello from thread %d\n", thread_id);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int thread_ids[5];
for (int i = 0; i < 5; i++) {
thread_ids[i] = i;
if (pthread_create(&threads[i], NULL, print_hello, (void *)&thread_ids[i])) {
fprintf(stderr, "Error: unable to create thread %d\n", i);
exit(-1);
}
}
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
printf("Finished all threads\n");
return 0;
}
這個程序創建了5個線程,每個線程都會打印一條消息。
打開終端,導航到包含multithread_example.c
的目錄。
使用以下命令編譯源文件:
gcc -pthread multithread_example.c -o multithread_example
這里,-pthread
選項告訴GCC鏈接線程庫,以便正確地編譯多線程程序。
./multithread_example
你應該會看到類似以下的輸出:
Hello from thread 0
Hello from thread 1
Hello from thread 2
Hello from thread 3
Hello from thread 4
Finished all threads
這就是在Ubuntu下使用GCC編譯多線程程序的方法。