One advantage to using threads is that they can execute for a very long time without preventing the execution of your main thread/application. The downside is that threads that execute without an end can end up consuming too much CPU.
In some cases, however, the user might need the thread to perform an action and then release its access to the CPU to allow another thread to perform its task. To accomplish this, we use the pthread_yield() API, which takes the following form:
Syntax:
int pthread_yield(void);
Returns 0 on success and error value on error.
Example Code
Consider the example shown below:
#include <stdio.h> #include <pthread.h> pthread_t tid[2]; void *thread_fn1(void *arg) { int err = pthread_yield(); perror("pthread_yield"); printf("Thread 1 in execution\n"); pthread_exit(NULL); } void *thread_fn2(void *arg) { printf("Thread 2 in execution\n"); pthread_exit(NULL); } int main() { int ret; ret = pthread_create(&tid[0], NULL, thread_fn1, NULL); if (!ret) printf("Thread[%d] created Successfully\n",1); else printf("Thread[%d] not created\n",1); ret = pthread_create(&tid[1], NULL, thread_fn2, NULL); if (!ret) printf("Thread[%d] created Successfully\n",2); else printf("Thread[%d] not created\n",2); pthread_exit(NULL); }
Note: Although this function is provided, it should be noted that the operating system is excellent at handling threads that must perform a lot of work, and pthread_yield() should only be used when the user explicitly understands how it might provide optimization in their specific use case (since overuse of the pthread_yield() function can actually result in performance degradation).
It should also be noted that pthread_yield() is not available on all Unix systems.