C linux pthread thread priority

假装没事ソ 提交于 2019-12-03 16:32:27

问题


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?


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/5374902/c-linux-pthread-thread-priority

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!