Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C linux pthread thread priority

My program has one background thread that fills and swaps the back buffer of a double buffer implementation. The main thread uses the front buffer to send out data. The problem is the main thread gets more processing time on average when I run the program. I want the opposite behavior since filling the back buffer is a more time consuming process then processing and sending out data to the client.

How can I achieve this with C POSIX pthreads on Linux?

like image 243
eat_a_lemon Avatar asked Mar 21 '11 07:03

eat_a_lemon


4 Answers

In my experience, if, in the absence of prioritisation your main thread is getting more CPU then this means one of two things:

  1. it actually needs the extra time, contrary to your expectation, or

  2. the background thread is being starved, perhaps due to lock contention

Changing the priorities will not fix either of those.

like image 199
Alnitak Avatar answered Oct 15 '22 15:10

Alnitak


have a look at pthread_setschedparam() --> http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_setschedparam.3.html

pthread_setschedparam(pthread_t thread, int policy,
                         const struct sched_param *param);

You can set the priority in the sched_priority field of the sched_param.

like image 29
cordellcp3 Avatar answered Oct 15 '22 16:10

cordellcp3


Use pthread_setschedprio(pthread_t thread, int priority). But as in other cases (setschedparam or when using pthread_attr_t) your process should be started under root, if you want to change priorities (like nice utility).

like image 1
maverik Avatar answered Oct 15 '22 16:10

maverik


You should have a look at the pthread_attr_t struct. It's passed as a parameter to the pthread_create function. It's used to change the thread attributes and can help you to solve your problem.

If you can't solve it you will have to use a mutex to prevent your main thread to access your buffer before your other thread swaps it.

like image 1
Opera Avatar answered Oct 15 '22 17:10

Opera