在C++ 11中设置std :: thread priority的便携方式

Ger*_*ner 45 c++ portability c++11 thread-priority stdthread

在后C++ 11世界中设置std :: thread实例优先级的正确方法是什么

是否有一种可移植的方式,至少在Windows和POSIX(Linux)环境中有效?

或者是获取句柄并使用特定操作系统可用的本机调用的问题?

Mik*_*our 48

没有办法通过C++ 11库设置线程优先级.我不认为这会在C++ 14中发生变化,而我的水晶球在此之后对于版本的评论太朦胧了.

在POSIX中, pthread_setschedparam(thread.native_handle(), policy, {priority});

我不知道相同的Windows功能,但我确信必须有一个.

  • 另外一个不想知道它是如何在Windows上完成的. (19认同)
  • 减去一个因为不想知道它是如何在Windows中完成的.另外一个用于了解它,不能通过C++ 11轻松完成. (14认同)

mar*_*arc 22

我的快速实施......

#include <thread>
#include <pthread.h>
#include <iostream>
#include <cstring>

class thread : public std::thread
{
  public:
    thread() {}
    static void setScheduling(std::thread &th, int policy, int priority) {
        sch_params.sched_priority = priority;
        if(pthread_setschedparam(th.native_handle(), policy, &sch_params)) {
            std::cerr << "Failed to set Thread scheduling : " << std::strerror(errno) << std::endl;
        }
    }
  private:
    sched_param sch_params;
};
Run Code Online (Sandbox Code Playgroud)

这就是我用它的方式......

// create thread
std::thread example_thread(example_function);

// set scheduling of created thread
thread::setScheduling(example_thread, SCHED_RR, 2);
Run Code Online (Sandbox Code Playgroud)

  • 实际上@MarkusMayr​​这对于展示真实的实现非常有用.其他答案只提到了功能,但从未展示过适当的例子.它可能不是惯用语,但我相信它演示了为特定线程设置优先级的概念.至少 - 它帮助了我. (10认同)
  • 另一个完整的示例:https://en.cppreference.com/w/cpp/thread/thread/native_handle (3认同)

Die*_*ühl 10

标准C++库未定义对线程优先级的任何访问.要设置线程属性你会使用std::threadnative_handle(),并使用它,例如,POSIX系统上pthread_getschedparam()pthread_setschedparam().我不知道是否有任何建议将调度属性添加到线程接口.


Rod*_*atz 6

在Windows中,进程按类和级别优先级进行组织.阅读:调度优先级,它提供了有关线程和进程优先级的良好整体知识.您可以使用以下函数甚至动态控制优先级:GetPriorityClass(),SetPriorityClass(),SetThreadPriority(),GetThreadPriority().

Apperantly你也可以使用std::threadnative_handle()pthread_getschedparam()pthread_setschedparam()在Windows系统上.检查这个例子,std :: thread:Native Handle并注意添加的头文件!