0

I have created a function to set attributes of a pthread before calling pthread_create(). However, pthread_create() is failing as it returns non-zero value. I am not sure what is wrong with the attributes set by my function. I am compiling my program with g++ on Ubuntu 16.04 LTS.

To compile and execute i am using:

g++ example.cpp -lpthread
./a.out

-

typedef void *(*DART_TASK_T)(void *);
typedef void (*DART_CALLBACK_T)(int);

static struct taskcontrolblock_s sysTask[MAX_DARTOS_THREADS];
static unsigned max_task_id_registered = 0;

static std :: bitset<sizeInBytes(MAX_DARTOS_THREADS)> taskIDs;

struct taskcontrolblock_s {
    const char *name;

    DART_TASK_T routine;
    DART_CALLBACK_T cleanup_callback;

    void *arg;
    unsigned arg_len;

    union {
        uint8_t flags;
        struct {
        //uint8_t created:1;
        //uint8_t running:1;
        //uint8_t blocked:1;
        //uint8_t suspended:1;
        //uint8_t killed:1;
        //uint8_t completed:1;
        //uint8_t;
        }; 
    };

    int priority; 

    pthread_t thread;
}__attribute__((packed));


static int dispatch_task(int tid)
{
    if (!taskIDs[tid]) // 
        return -1;

    pthread_attr_t attr;
    struct sched_param param;
    param.sched_priority = sysTask[tid].priority;
    int policy = SCHED_RR;

    if (pthread_attr_init(&attr))
        return -1;
    if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED))
        return -1;
    if (pthread_attr_setschedpolicy(&attr, policy))
        return -1;
    if (pthread_attr_setschedparam(&attr, &param))
        return -1;
    if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM))
        return -1;

    if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
        return -1;

    if (pthread_create(&sysTask[tid].thread, &attr, sysTask[tid].routine, sysTask[tid].arg))
    return -1;

    pthread_attr_destroy(&attr);
    return 0;
}

Edit:

Calling perror() prints the character array Operation not permitted to the stderr.

Running the program with root privilege solved the problem.

abhiarora
  • 9,743
  • 5
  • 32
  • 57

1 Answers1

2

The first part of the answer is that to use SCHED_RR you must have CAP_SYS_NICE for your user. As you have noted, running as root makes it work. But you can run as any user so long as you have the CAP_SYS_NICE "capability." One way to get that is using setcap which is explained here: https://stackoverflow.com/a/37528755/4323

You will need the ability to run sudo setcap.

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436