pthread_setschedparam在使用mingw64的GCC上不起作用

im9ewurl  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(134)

我尝试在安装了GCC v13.2.0(MSYS2,UCRT运行时)的Windows 11上运行here的示例代码:

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

std::mutex iomutex;
void f(int num)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));

    sched_param sch;
    int policy;
    pthread_getschedparam(pthread_self(), &policy, &sch);
    std::lock_guard<std::mutex> lk(iomutex);
    std::cout << "Thread " << num << " is executing at priority " << sch.sched_priority << '\n';
}

int main()
{
    std::thread t1(f, 1), t2(f, 2);

    sched_param sch;
    int policy;
    pthread_getschedparam(t1.native_handle(), &policy, &sch);
    sch.sched_priority = 20;
    int result = pthread_setschedparam(t1.native_handle(), SCHED_FIFO, &sch);
    if (result)
        std::cout << "Failed to setschedparam: " << std::strerror(result) << '\n';

    t1.join();
    t2.join();
}

字符串
代码会编译,但输出是:

Failed to setschedparam: not supported
Thread 2 is executing at priority 0
Thread 1 is executing at priority 0


即使以管理员身份运行也会发生这种情况。与在Ubuntu上运行相同的代码相比,它会输出(仅在使用sudo时):

Thread 1 is executing at priority 20
Thread 2 is executing at priority 0


我使用了g++ -v,并验证了GCC是用--enable-threads=posix配置的,并明确表示“线程模型:posix”。为什么这段代码不起作用?是winpthread中的bug,还是即使使用pthreads,在Windows上设置优先级的工作方式也不同?
更新:我修改了上面的代码,根据pthread_setschedparam的返回值打印出错误,正如评论中的“n.m.可能是AI”所建议的那样。

carvr3hs

carvr3hs1#

我在回答我自己的问题,基于n. m. could be an AI的评论。
首先,mingw64似乎只支持SCHED_OTHER的调度策略。其次,即使在Linux上最大线程优先级是99,在Windows上它是15。这可以通过运行sched_get_priority_max(policy)来获得,它返回15。(或者,如果我们包含windows.h,它将THREAD_PRIORITY_TIME_CRITICAL定义为15,并且该宏可以直接与pthread_setschedparam一起使用。
下面是代码的更正版本:

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

std::mutex iomutex;
void f(int num)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));

    sched_param sch;
    int policy;
    pthread_getschedparam(pthread_self(), &policy, &sch);
    std::lock_guard<std::mutex> lk(iomutex);
    std::cout << "Thread " << num << " is executing at priority " << sch.sched_priority << '\n';
}

int main()
{
    std::thread t1(f, 1), t2(f, 2);

    sched_param sch;
    int policy;
    pthread_getschedparam(t1.native_handle(), &policy, &sch);
    int max_priority = sched_get_priority_max(policy);
    std::cout << "The maximum thread priority on this system is: " << max_priority << '\n';
    sch.sched_priority = max_priority;
    int result = pthread_setschedparam(t1.native_handle(), SCHED_OTHER, &sch);
    if (result)
        std::cout << "Failed to setschedparam: " << std::strerror(result) << '\n';

    t1.join();
    t2.join();
}

字符串

相关问题