C linux pthread线程优先级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5374902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:21:13  来源:igfitidea点击:

C linux pthread thread priority

clinuxmultithreadingpthreadsthread-priority

提问by eat_a_lemon

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?

如何在 Linux 上使用 C POSIX pthreads 实现这一点?

采纳答案by Alnitak

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

根据我的经验,如果在没有优先级的情况下,您的主线程获得更多 CPU,那么这意味着以下两种情况之一:

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

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

  1. 它实际上需要额外的时间,与您的期望相反,或者

  2. 后台线程正在挨饿,可能是由于锁争用

Changing the priorities will not fix either of those.

改变优先级不会解决其中任何一个问题。

回答by cordellcp3

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

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

您可以在 sched_pa​​ram 的 sched_priority 字段中设置优先级。

回答by Opera

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

你应该看看pthread_attr_t结构。它作为参数传递给pthread_create函数。它用于更改线程属性,可以帮助您解决问题。

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.

如果您无法解决它,您将不得不使用互斥锁来防止您的主线程在其他线程交换它之前访问您的缓冲区。

回答by maverik

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_setschedprio(pthread_t thread, int priority). 但是在其他情况下(setschedparam 或使用 pthread_attr_t 时),如果您想更改优先级(如 nice 实用程序),您的进程应该在 root 下启动。