C linux pthread 线程优先级
我的程序有一个后台线程,用于填充和交换双缓冲区实现的后台缓冲区。 主线程使用前缓冲区发送数据。问题是当我运行程序时,主线程平均获得更多的处理时间。我想要相反的行为,因为填充后台缓冲区是一个比处理数据并向客户端发送数据更耗时的过程。
如何在 Linux 上使用 C POSIX pthreads 实现此目的?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据我的经验,如果在没有优先级的情况下,您的主线程获得更多的 CPU,那么这意味着以下两件事之一:
它实际上需要额外的时间,与您的预期相反,或者
后台线程正在饥饿,可能是由于锁争用
更改优先级不会修复其中任何一个。
In my experience, if, in the absence of prioritisation your main thread is getting more CPU then this means one of two things:
it actually needs the extra time, contrary to your expectation, or
the background thread is being starved, perhaps due to lock contention
Changing the priorities will not fix either of those.
看看 pthread_setschedparam() --> http://www.kernel.org/doc /man-pages/online/pages/man3/pthread_setschedparam.3.html
您可以在 sched_param 的 sched_priority 字段中设置优先级。
have a look at pthread_setschedparam() --> http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_setschedparam.3.html
You can set the priority in the sched_priority field of the sched_param.
使用pthread_setschedprio(pthread_t线程,int优先级)。但与其他情况一样(setschedparam 或使用 pthread_attr_t 时),如果您想更改优先级(例如 Nice 实用程序),您的进程应该在 root 下启动。
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).您应该查看
pthread_attr_t
结构。它作为参数传递给pthread_create
函数。它用于更改线程属性,可以帮助您解决问题。如果您无法解决它,则必须使用互斥锁来防止主线程在其他线程交换缓冲区之前访问缓冲区。
You should have a look at the
pthread_attr_t
struct. It's passed as a parameter to thepthread_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.