Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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).

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top