centos

GCC在CentOS中如何编译多线程程序

小樊
41
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
看了该问题的人还看了