为什么使用-lpthread隐式声明pthread_yield,而所有使用-pthread都可以? [英] Why implicit declaration of pthread_yield with -lpthread while all ok with -pthread?

查看:1465
本文介绍了为什么使用-lpthread隐式声明pthread_yield,而所有使用-pthread都可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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

给出


警告:隐式声明函数'pthread_yield'[-Wimplicit-function-declaration]





  1. Can第二 a.out 仍然正常运行?

  2. 如何解决警告而不是 -pthread ?是 sched_yield 另一种产生pthread的方法?


解决方案这是一个非标准的函数,通常可以通过定义

> #define _GNU_SOURCE

尽管您应该使用 - pthread 用于编译,我希望你可以用两个编译(除非 -pthread define _GNU_SOURCE 可能是这种情况)。

正确的解决方法是不使用 非标准函数 pthread_yield()并使用POSIX函数 sched_yield() ,而不是包含 #include< sched.h>


I compile this code main.c in CentOS7 with gcc:

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

1st compile: gcc -Wall -g main.c -pthread -o a.out
It's all OK.

2nd compile: gcc -Wall -g main.c -lpthread -o a.out
Gives

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

  1. Can the 2nd a.out still run correctly ?
  2. How to fix the warning without -pthread? Is sched_yield another way to yield a pthread ?

解决方案

pthread_yield() is a non-standard function which is typically enabled by defining

#define _GNU_SOURCE

While you should use -pthread for compiling, I would expect you to get the same warning with both compilations (unless -pthread defines _GNU_SOURCE which may be the case).

The correct way to fix is to not use the non-standard function pthread_yield() and use the POSIX function sched_yield() instead by including #include <sched.h>.

这篇关于为什么使用-lpthread隐式声明pthread_yield,而所有使用-pthread都可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆