在 C++11 中为 pthread 设置调度参数
Set scheduling parameters for a pthread in c++11
我很想给我的程序的主线程一个更高的调度优先级。我用 c++11 线程试过了,但失败了……
我正在使用 Raspbian 拉伸
这是针对主线程的:
sched_param sch;
int policy;
pthread_getschedparam(pthread_self(), &policy, &sch);
sch.sched_priority = 10;
if (pthread_setschedparam(pthread_self(), SCHED_FIFO, &sch)) {
std::cout << "Failed to setschedparam: " << std::strerror(errno) << std::endl;
}
这是一个 c++11 线程:
std::unique_ptr<std::thread> Stream;
Stream = std::make_unique<std::thread>([&, this]
{
while (!finished)
{
std::this_thread::sleep_for(std::chrono::milliseconds(2));
/* more code */
}
});
sched_param sch;
int policy;
pthread_getschedparam(Stream->native_handle(), &policy, &sch);
sch.sched_priority = 20;
if (pthread_setschedparam(Stream->native_handle(), SCHED_OTHER, &sch))
{
std::cout << "Failed to setschedparam: " << std::strerror(errno) << std::endl;
}
我得到 Invalid argument
但我不明白为什么...
祝福
如果策略是 unrecognized/unsupported 或参数没有意义,则返回 EINVAL。 SCHED_OTHER 仅对优先级为 0 的线程有意义。您 运行 的行为是类 FreeBSD 系统的典型行为,它们不会忽略 sched_param::priority
非零值。
我很想给我的程序的主线程一个更高的调度优先级。我用 c++11 线程试过了,但失败了……
我正在使用 Raspbian 拉伸
这是针对主线程的:
sched_param sch;
int policy;
pthread_getschedparam(pthread_self(), &policy, &sch);
sch.sched_priority = 10;
if (pthread_setschedparam(pthread_self(), SCHED_FIFO, &sch)) {
std::cout << "Failed to setschedparam: " << std::strerror(errno) << std::endl;
}
这是一个 c++11 线程:
std::unique_ptr<std::thread> Stream;
Stream = std::make_unique<std::thread>([&, this]
{
while (!finished)
{
std::this_thread::sleep_for(std::chrono::milliseconds(2));
/* more code */
}
});
sched_param sch;
int policy;
pthread_getschedparam(Stream->native_handle(), &policy, &sch);
sch.sched_priority = 20;
if (pthread_setschedparam(Stream->native_handle(), SCHED_OTHER, &sch))
{
std::cout << "Failed to setschedparam: " << std::strerror(errno) << std::endl;
}
我得到 Invalid argument
但我不明白为什么...
祝福
如果策略是 unrecognized/unsupported 或参数没有意义,则返回 EINVAL。 SCHED_OTHER 仅对优先级为 0 的线程有意义。您 运行 的行为是类 FreeBSD 系统的典型行为,它们不会忽略 sched_param::priority
非零值。