androidcpthreadsthread-priority

pthread_create warning on android


After calling pthread_create function I receive next message:

W/libc (26409): pthread_create sched_setscheduler call failed: Operation not permitted

The code used to create the thread is:

pthread_attr_t threadAttr;
int ret = pthread_attr_init(&threadAttr);
//code to check ret - it's 0

size_t guard_size = 0;
pthread_attr_getguardsize(&threadAttr, &guard_size);
ret = pthread_attr_setstacksize(&threadAttr, myStackSize + guard_size);
//code to check ret - it's 0

ret = pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
//code to check ret - it's 0

ret = pthread_attr_setschedpolicy(&threadAttr, SCHED_FIFO);
//code to check ret - it's 0

sched_param  schedParam;
schedParam.sched_priority = myPriority; //it's 16
ret = pthread_attr_setschedparam(&threadAttr, &schedParam);
//code to check ret - it's 0

// Create the thread
ret = pthread_create(&myHandle, &threadAttr, RunCallback, (void *)myData);
//code to check ret - it's 0
//code to check myHandle - it's > 0

// Delete attribute
pthread_attr_destroy(&threadAttr);

Please note that the message appears in logcat before breakpoint in RunCallback is hit.

Do you know why I have this warning? Is it safe to ignore it - if yes why?

PS: code runs as native activity on Nexus 4 devices with 4.4.2 OS version(build number KOT49H).


Solution

  • When you call pthread_attr_setschedpolicy, you're requesting that a specific scheduling policy should be set (http://man7.org/linux/man-pages/man3/pthread_attr_setschedpolicy.3.html). The policy you're setting, SCHED_FIFO, is a real-time policy according to http://man7.org/linux/man-pages/man2/sched_setscheduler.2.html. Setting the scheduling policy to a real-time policy requires the CAP_SYS_NICE capability according to http://man7.org/linux/man-pages/man7/capabilities.7.html. Therefore, the pthread_attr_setschedpolicy call will fail unless you have that capability.

    To solve the problem, either drop the scheduler attribute (and live with the default scheduling), or ensure that your process is started with the correct capabilities (e.g. by starting it as root and dropping all privileges except for CAP_SYS_NICE).