线程显式调度POSIX API给出错误

时间:2017-10-22 13:00:38

标签: c multithreading gcc

我试图创建一些线程,其中一些线程将遵循开发人员提供的显式调度设置并编写以下代码:

pthread_t thid1,thid2,thid3,thid4;

int main()
{

   int ret;
   struct sched_param param1;

   pthread_attr_t pthread_attr1,pthread_attr4;

   ret = pthread_attr_init(&pthread_attr4); 
      if(ret>0) { 
              printf("error in the thread attr initialization\n");  
      }

   ret = pthread_create(&thid4,&pthread_attr4,display_status_thread,NULL);

   if(ret>0) { printf("error in thread creation for producer\n"); exit(4); }   


   pthread_attr_init(&pthread_attr1); 

   //setting the policy to realtime, priority based 
   pthread_attr_setschedpolicy(&pthread_attr1,SCHED_FIFO);

   //realtime priority of 1 ( 1-99 is the range) 
   param1.sched_priority = 20;
   pthread_attr_setschedparam(&pthread_attr1, &param1);  

   ret = pthread_attr_setinheritsched(&pthread_attr1,PTHREAD_EXPLICIT_SCHED); 

   if(ret>0) { perror("pthread_attr_setinheritsched failed."); exit(1); }

   ret = pthread_create(&thid1,&pthread_attr1,func1,NULL);
   //Here comes error " error in creating func1 thread.
   if(ret>0) { printf("error in thread creation for func1\n"); exit(1); }

   ret = pthread_create(&thid2,NULL,func2,NULL);
   if(ret>0) { printf("error in thread creation for func2\n"); exit(2); } 

   ret = pthread_create(&thid3,NULL,func3,NULL);
   if(ret>0) { printf("error in thread creation for func3\n"); exit(3); } 


   pthread_join(thid1,NULL);

   pthread_join(thid2,NULL);

   pthread_join(thid3,NULL);

   pthread_join(thid4,NULL);

   exit(0);

}

我在设置继承调度创建显式线程的地方收到错误。

出了什么问题? pthread_attr_setinheritsched()的用法在语法或其他方面是否不正确?

由于

1 个答案:

答案 0 :(得分:0)

我很确定如果你出现错误

就会发现问题
  

错误顶部

   EAGAIN Insufficient resources to create another thread.

   EAGAIN A system-imposed limit on the number of threads was
          encountered.  There are a number of limits that may trigger
          this error: the RLIMIT_NPROC soft resource limit (set via
          setrlimit(2)), which limits the number of processes and
          threads for a real user ID, was reached; the kernel's system-
          wide limit on the number of processes and threads,
          /proc/sys/kernel/threads-max, was reached (see proc(5)); or
          the maximum number of PIDs, /proc/sys/kernel/pid_max, was
          reached (see proc(5)).

   EINVAL Invalid settings in attr.

   EPERM  No permission to set the scheduling policy and parameters
          specified in attr. ATTRIBUTES         top

这可能会打印正确的错误消息。

errno = ret; 
perror(msg); 
exit(EXIT_FAILURE);

修改:问题是EPERM,升级到sudo现在就运行了。