c - 为什么使用 -lpthread 隐式声明 pthread_yield 而使用 -pthread 则一切正常?

标签 c linux gcc pthreads

我在 CentOS7 中使用 gcc 编译此代码 main.c:

#include <pthread.h>
void* mystart(void* arg)
{
    pthread_yield();
    return(0);
}
int main(void)
{
    pthread_t pid;
    pthread_create(&pid, 0, mystart, 0);
    return(0);
}

第一次编译:gcc -Wall -g main.c -pthread -o a.out
一切都好。

第二次编译:gcc -Wall -g main.c -lpthread -o a.out
给予

warning: implicit declaration of function 'pthread_yield' [-Wimplicit-function-declaration]

  1. 第二个a.out还能正常运行吗?
  2. 如何在没有 -pthread 的情况下修复警告? sched_yield 是生成 pthread 的另一种方法吗?

最佳答案

pthread_yield()是一个非标准功能,通常通过定义

来启用
#define _GNU_SOURCE

虽然你应该使用-pthread对于编译,我希望您在两个编译中得到相同的警告(除非-pthread定义_GNU_SOURCE,这可能是这种情况)。

正确的修复方法是使用非标准函数pthread_yield()并使用 POSIX 函数 sched_yield() 相反,包括 #include <sched.h> .

关于c - 为什么使用 -lpthread 隐式声明 pthread_yield 而使用 -pthread 则一切正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822375/

相关文章:

c - 为什么这个程序不打印 '4' ?

每当使用除法时,C 程序中的计算结果总是为 0

linux - 使用 tcp 2222 :22 to copy things 时,用于内核开发的 QEMU 引导不起作用

c - c中的不同输出

c - 如何像在 Autotools 中一样检查 CMake 中的头文件和库函数?

c - 如何保护Linux中进程间共享的内存

linux - 需要帮助实现 Python 函数的自动化

c - 使用扩展汇编语法在实模式下调用 BIOS 服务存在困难

c - 有没有可以发现 C 源代码中潜在错误的工具?

c++ - 与 GCC 共享不一致的字符串文字