我试着编译一个包含线程的c文件。但我试图编译正常的方式这样为什么我们需要“-pthread”标志来编译c文件
的gcc -o线程thread.c -Wall
但它给出了一个错误。但我试图编译像这样
-pthread的gcc -o线程thread.c -Wall
它的工作。这个和-pthread标志的原因是什么? 下面
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
void *thread_function(void *arg)
{
int a;
for(a=0;a<10; a++)
{
printf("Thread says hi!\n");
sleep(2);
}
return NULL;
}
int main(void)
{
pthread_t mythread;
if (pthread_create(&mythread, NULL, thread_function, NULL))
{
printf("error creating thread.");
abort();
}
if (pthread_join (mythread, NULL))
{
printf("error joining thread.");
abort();
}
printf("Main thread says hi!\n");
exit(0);
}
你应该看看:https://stackoverflow.com/questions/23250863/difference-between-pthread-and-lpthread-while-compiling。从本质上讲,你需要告诉编译器链接到pthread库 – Mike
关于gcc文档的特别不清楚? – Olaf
阅读本文以供参考[https://randu.org/tutorials/threads/](https://randu.org/tutorials/threads/) –