在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编译多线程程序的方法。