Index: include/llvm/Support/Threading.h =================================================================== --- include/llvm/Support/Threading.h +++ include/llvm/Support/Threading.h @@ -167,6 +167,12 @@ /// purposes, and as with setting a thread's name no indication of whether /// the operation succeeded or failed is returned. void get_thread_name(SmallVectorImpl &Name); + + enum class ThreadPriority { + Background = 0, + Default = 1, + }; + void set_thread_priority(ThreadPriority Priority); } #endif Index: lib/Support/Unix/Threading.inc =================================================================== --- lib/Support/Unix/Threading.inc +++ lib/Support/Unix/Threading.inc @@ -217,3 +217,19 @@ #endif #endif } + +void llvm::set_thread_priority(ThreadPriority Priority) { + // Some *really* old glibcs are missing SCHED_IDLE. +#if defined(__linux__) && defined(SCHED_IDLE) + sched_param priority; + priority.sched_priority = 0; + pthread_setschedparam( + pthread_self(), + Priority == ThreadPriority::Background ? SCHED_IDLE : SCHED_OTHER, + &priority); +#elif defined(__APPLE__) + // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getpriority.2.html + setpriority(PRIO_DARWIN_THREAD, 0, + Priority == ThreadPriority::Background ? PRIO_DARWIN_BG : 0); +#endif +} Index: lib/Support/Windows/Threading.inc =================================================================== --- lib/Support/Windows/Threading.inc +++ lib/Support/Windows/Threading.inc @@ -106,3 +106,10 @@ // value. Name.clear(); } + +void llvm::set_thread_priority(ThreadPriority Priority) { + SetThreadPriority(GetCurrentThread(), + Priority == ThreadPriority::Background + ? THREAD_MODE_BACKGROUND_BEGIN + : THREAD_MODE_BACKGROUND_END); +}