gpt4 book ai didi

c - 为什么我们需要 "-pthread"标志来编译 c 文件

转载 作者:行者123 更新时间:2023-11-30 18:11:35 25 4
gpt4 key购买 nike

我尝试编译一个包含线程的c 文件。但我尝试像这样正常编译

gcc -o thread thread.c -Wall

但它给出了一个错误。但我尝试这样编译

gcc -pthread -o thread thread.c -Wall

它成功了。这是什么原因,-pthread 标志会做什么?下面是我的 C 代码

#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);
}

最佳答案

根据gcc引用:

-pthreads

Add support for multithreading using the POSIX threads library. This option sets flags for both the preprocessor and linker. This option does not affect the thread safety of object code produced by the compiler or that of libraries supplied with it.

关于c - 为什么我们需要 "-pthread"标志来编译 c 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46038167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com