ubuntu

ubuntu下gcc编译多线程程序方法

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