Linux多线程学习(七)sched_yield

sched_yield()这个函数可以使用另一个级别等于或高于当前线程的线程先运行。如果没有符合条件的线程,那么这个函数将会立刻返回然后继续执行当前线程的程序。  

在成功完成之后返回零,否则返回-1.

看下面一个实例

#define _MULTI_THREADED
#include 
#include 
#include 

#define            LOOPCONSTANT     1000
#define            THREADS          3

pthread_mutex_t    mutex = PTHREAD_MUTEX_INITIALIZER;
int                i,j,k,l;
static void checkResults(char *string, int rc) {
  if (rc) {
    printf("Error on : %s, rc=%d",
           string, rc);
    exit(EXIT_FAILURE);
  }
  return;
}
void *threadfunc(void *parm){ int loop = 0; int localProcessingCompleted = 0; int numberOfLocalProcessingBursts = 0; int processingCompletedThisBurst = 0; int rc; printf("Entered secondary thread\n"); for (loop=0; loopsched_yield(). */ sched_yield(); } printf("Finished secondary thread\n"); return NULL;}int main(int argc, char **argv){ pthread_t threadid[THREADS]; int rc=0; int loop=0; printf("Enter Testcase - %s\n", argv[0]); rc = pthread_mutex_lock(&mutex); checkResults("pthread_mutex_lock()\n", rc); printf("Creating %d threads\n", THREADS); for (loop=0; loop

运行结果 Enter Testcase - ./sched_yield

Creating 3 threads
Entered secondary thread
Entered secondary thread
Entered secondary thread
Wait for results
Finished secondary thread
Finished secondary thread
Finished secondary thread
Main completed

你可能感兴趣的:(linux多线程)