溫馨提示×

ubuntu下gcc編譯多線程程序方法

小樊
46
2025-06-27 06:42:08
欄目: 智能運維

在Ubuntu下使用GCC編譯多線程程序,你需要使用-pthread選項。這是一個示例:

  1. 首先,創建一個名為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個線程,每個線程都會打印一條消息。

  1. 打開終端,導航到包含multithread_example.c的目錄。

  2. 使用以下命令編譯源文件:

gcc -pthread multithread_example.c -o multithread_example

這里,-pthread選項告訴GCC鏈接線程庫,以便正確地編譯多線程程序。

  1. 運行生成的可執行文件:
./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編譯多線程程序的方法。

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