溫馨提示×

ubuntu gcc編譯多線程程序方法

小樊
57
2025-06-04 22:37:40
欄目: 智能運維

在Ubuntu上使用GCC編譯多線程程序,你需要使用-pthread選項。這將啟用線程支持,鏈接pthread庫,并設置適當的編譯器標志。下面是一個簡單的示例:

  1. 首先,創建一個名為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);
}
  1. 使用以下命令編譯此程序:
gcc -pthread multithread_example.c -o multithread_example

這里,-pthread選項告訴GCC啟用線程支持,鏈接pthread庫,并設置適當的編譯器標志。multithread_example.c是源文件名,-o multithread_example表示將編譯后的程序命名為multithread_example。

  1. 運行編譯后的程序:
./multithread_example

這將輸出以下內容:

Thread 1
Thread 2
Thread 1 ends.
Thread 2 ends.

這就是在Ubuntu上使用GCC編譯多線程程序的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女