为什么使用RR或FIFO调度程序LINUX UBUNTU时pthread_Join不起作用

时间:2020-01-26 11:09:34

标签: c linux pthreads

因此,我修改了pthread_attr_setdetachstate的IBM示例代码以更好地了解如何使用它,我注意到,如果将线程策略设置为SCHED_RR或SCHED_FIFO,则main函数不会等待线程完成然后退出。

但是,如果我将策略设置为SCHED_OTHER,它将等待线程完成。

为什么会这样?

/* CELEBP11 */
#define _OPEN_THREADS
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <sys/time.h>

void **stat;
void *thread1(void *arg)
{
   printf("hello from the thread\n");
   pthread_exit((void *)0);
}

int main()
{
   int            ds, rc;
   size_t         s1;
   pthread_attr_t attr;
   pthread_t      thid;

   rc = pthread_attr_init(&attr);
   if (rc == -1) {
      perror("error in pthread_attr_init");
      exit(1);
   }
   rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
   if (rc == -1) {
      perror("error in pthread_attr_setdetachstate");
      exit(2);
   }

   rc = pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED);
   if (rc == -1) {
      perror("error in pthread_attr_setdetachstate");
      exit(4);
   }


   rc = pthread_attr_setschedpolicy (&attr, SCHED_RR);
   if (rc != 0) {
      perror("error in pthread_attr_setschedpolicy");
      exit(5);
   }

   struct sched_param param_test;

   param_test.sched_priority = 50;

   rc = pthread_attr_setschedparam(&attr, &param_test);
   if (rc == -1) {
      perror("error in pthread_attr_setschedparam");
      exit(6);
   }

   rc = pthread_create(&thid, &attr, thread1, NULL);
   if (rc == -1) {
      perror("error in pthread_create");
      exit(3);
   }


   rc = pthread_join(thid, stat);
   exit(0);
}

要编译

gcc test.c -lpthread -lrt   -o test2

0 个答案:

没有答案