pthread_create与pthread_attr_setschedparam无法正常工作

时间:2013-02-20 20:53:17

标签: c++ linux pthreads

我是线程编程的新手。所以我为这个看似愚蠢的问题道歉。

我正在尝试使用pthread_cretr()使用pthread_attr_t创建一个POSIX线程。我正在尝试设置sched_priority值并将其放在属性中。代码粘贴在下面:

#include <iostream>
#include <cstring>
#include <pthread.h>
using namespace std;

void* log(void* arg)
{

  FILE *fp = fopen("/tmp/log.txt", "w+");
   if (fp != NULL)
   {
     fputs("Logging with Thread", fp);
    }
   else
   {
    cout <<"file pointer not created" << endl;
   }
   return 0;
 }
int main(int argc, char** argv )
{

  pthread_t th;
  pthread_attr_t th_attr;
  int policy;
  struct sched_param thparam;
  memset(&thparam, 0,sizeof(sched_param));
  int retval = pthread_attr_init(&th_attr);
  if (0 != retval)
   {
     cout <<"Attribute initialization failed" << endl;
   }

  thparam.sched_priority = 10;

  int ret1 = pthread_attr_setschedparam(&th_attr, &thparam);
  if (0 == ret1)
  {
   cout <<"pthread_attr_setschedparam PASSED" << endl;
   } 

 int ret = pthread_create(&th, &th_attr, log, NULL);
 if (0 != ret)
  {
   cout <<"thread not created" << endl;      
  }
 else
  {
   cout <<"Thread created" << endl;
  }

  int retval1 = pthread_getschedparam(th, &policy, &thparam);
  if (0 != retval1)
  {
   cout <<"Inside Main::pthread_getschedparam FAILED at start" << endl;
  }
  else
  {
   cout <<"Inside Main::priority: " << thparam.sched_priority << endl;
   cout <<"Inside Main::sched policy: " << policy << endl;
  }
  pthread_join(th, NULL);

  return (0);
 }

每次运行此程序时,都会创建线程,但默认优先级(在我的情况下为15)。由于我已将优先级设置为10,因此应以10优先级开始。我不明白为什么会这样。我打印的所有日志消息都是预期的,似乎没有错误。 谁能指出我在代码中做错了什么?

感谢!!!!

编辑:

我似乎发现了一件有趣的事情。我无法在创建线程期间设置线程优先级。但是我可以在创建线程后更改线程的优先级。我使用API​​ pthread_setschedparam来设置优先级。这次线程的优先级正确地改变了。仍然无法理解为什么会这样。

我还应该提一下,我使用的是ARM拱形嵌入式系统。我还将调度程序策略设置为SCHED_RR。

有人可以解释为什么会这样吗?

3 个答案:

答案 0 :(得分:0)

你确定你看到了这个输出吗?

pthread_attr_setschedparam PASSED

您没有检查pthread_attr_setschedparam调用错误,我认为它可能会返回EINVAL,因此线程的优先级没有被更改。

Linux手册页声称功能总是成功,但是当我测试你的代码时,情况并非如此。

答案 1 :(得分:0)

尝试这样的事情:

pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

答案 2 :(得分:0)

从手册页:

   In order for the parameter setting made by
   pthread_attr_setschedparam() to have effect when calling
   pthread_create(3), the caller must use
   pthread_attr_setinheritsched(3) to set the inherit-scheduler
   attribute of the attributes object attr to PTHREAD_EXPLICIT_SCHED.