溫馨提示×

GCC在CentOS中如何編譯多線程程序

小樊
54
2025-05-24 22:34:35
欄目: 智能運維

在CentOS中使用GCC編譯多線程程序,你需要使用-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;

    /* 創建兩個線程 */
    if (pthread_create(&thread1, NULL, print_hello, (void *) message1) != 0)
        perror("Unable to create thread 1");
    if (pthread_create(&thread2, NULL, print_hello, (void *) message2) != 0)
        perror("Unable to create thread 2");

    /* 等待線程結束 */
    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

這將創建兩個線程,每個線程都會打印一條消息。

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