linux的gcc编译多线程
时间: 2023-10-18 12:15:38 浏览: 40
在 Linux 中使用 gcc 编译多线程程序,需要使用 POSIX 标准库中的线程相关函数。以下是一个简单的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 4
void *print_hello(void *thread_id) {
long tid = (long)thread_id;
printf("Hello from thread %ld\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void *)t);
if (rc) {
printf("Error: unable to create thread, %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
```
在这个程序中,我们创建了 NUM_THREADS 个线程,并且每个线程都会打印一条消息。我们使用 pthread_create() 函数创建线程,并且将线程 ID 作为参数传递给 print_hello() 函数。
要编译这个程序,可以使用以下命令:
```
gcc -pthread -o program program.c
```
其中 -pthread 选项告诉编译器链接 POSIX 线程库。然后我们可以运行程序:
```
./program
```
程序将输出类似以下的内容:
```
Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Hello from thread 0
Hello from thread 1
Hello from thread 2
Hello from thread 3
```
这表明程序成功创建了四个线程,并且每个线程都打印了一条消息。