9

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 ?
Spikatrix
  • 20,225
  • 7
  • 37
  • 83
linrongbin
  • 2,967
  • 6
  • 31
  • 59

2 Answers2

9

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>.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    Only difference -pthread makes on linux is it adds a `#define _REENTRANT 1` – nos Aug 24 '15 at 13:57
  • That's the only difference I see as well. But OP reports he does not get the warning with `-pthread` which I find odd. – P.P Aug 24 '15 at 14:22
  • It's my mistake, it's true that both -pthread and -lpthread will generate the warning 'implicit of pthread_yield'. – linrongbin Aug 26 '15 at 08:57
  • 1
    @zhaochenyou Right. Thanks for the confirmation. That's what I expected. So you can either define `_GNU_SOURCE` before including any headers if you want to use the non-standard function `pthread_yield()`. Or better yet, use `sched_yield()`. – P.P Aug 26 '15 at 09:01
5

You should use -pthread for compile and link. It not only links the library, it also sets preprocessor defines and sometimes selects a different runtime library (on Windows for example).

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • my 2nd question is the difference between: pthread_yield and sched_yield. are they behave the same? – linrongbin Aug 24 '15 at 05:23
  • 1
    @zhaochenyou: One question per question. That is the rule. Also, it is the only way you get your questions correctly answered. – Zan Lynx Aug 24 '15 at 05:23