在Ubuntu上使用GCC編譯多線程程序,你需要使用-pthread
選項。這將啟用線程支持,鏈接pthread庫,并設置適當的編譯器標志。下面是一個簡單的示例:
multithread_example.c
的源文件,內容如下:#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_hello(void *ptr) {
char *message;
message = (char *) ptr;
printf("%s \n", message);
pthread_exit(NULL);
}
int main(void) {
pthread_t thread1, thread2;
char *message1;
char *message2;
message1 = (char *) malloc(sizeof(char) * 18);
message2 = (char *) malloc(sizeof(char) * 18);
strcpy(message1, "Thread 1");
strcpy(message2, "Thread 2");
int i1, i2;
/* 創建兩個線程 */
i1 = pthread_create(&thread1, NULL, print_hello, (void *) message1);
i2 = pthread_create(&thread2, NULL, print_hello, (void *) message2);
/* 等待兩個線程結束 */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Thread 1 ends.\n");
printf("Thread 2 ends.\n");
exit(0);
}
gcc -pthread multithread_example.c -o multithread_example
這里,-pthread
選項告訴GCC啟用線程支持,鏈接pthread庫,并設置適當的編譯器標志。multithread_example.c
是源文件名,-o multithread_example
表示將編譯后的程序命名為multithread_example
。
./multithread_example
這將輸出以下內容:
Thread 1
Thread 2
Thread 1 ends.
Thread 2 ends.
這就是在Ubuntu上使用GCC編譯多線程程序的方法。