5

I have a program structured as follows, and it's a massive CPU hog. IO slows down for the whole system, I can hardly move the mouse pointer...

...why? I thought THREAD_MODE_BACKGROUND_BEGIN should prevent this?

#pragma omp parallel 
{
    SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);

    #pragma omp for 
    for (...)
    {
        doTruckLoadsOfComputation();
        if (omp_get_thread_num()==0)
            doTinyAmountOfIO(); //progress indicator
    }
    SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
}

UPDATE:

Adding SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); fixes the CPU hogging issue but the question still stands, why wasn't background mode alone sufficient?

Sideshow Bob
  • 4,566
  • 5
  • 42
  • 79
  • What happens if you bring another window to the foreground / minimise the application? – OMGtechy Mar 30 '16 at 12:57
  • I can't, the other window doesn't even come to foreground. – Sideshow Bob Mar 30 '16 at 13:26
  • 1
    Dumb question: What OS are you running on? [`THREAD_MODE_BACKGROUND_BEGIN`/`END` isn't supported prior to Vista](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686277%28v=vs.85%29.aspx), so an old WS03 machine probably wouldn't work. It might help to actually check the return value from `SetThreadPriority` to make sure it succeeded. It's also unclear whether background mode actually affects CPU scheduling priority; it looks like it's an addon that changes I/O priority (which other settings don't), but the exact behavior isn't properly documented. – ShadowRanger Mar 30 '16 at 13:34
  • 1
    Background vs. Foreground is a bit more nuanced than the `SetThreadPriority` implies. This old article, although dated now, explains it better: https://support.microsoft.com/en-us/kb/259025 . A 'background' thread can still steal 100% CPU – Remus Rusanu Mar 30 '16 at 13:47
  • @ShadowRanger not a dumb question, but Win7 – Sideshow Bob Mar 30 '16 at 14:30
  • 1
    I have just noticed `doTinyAmountOfIO`. How many times do you call this? What happens if you remove it? – zdf Mar 30 '16 at 15:34
  • I just noticed in Remus' link above that even a tiny amount of IO will cause a priority boost, which may explain *everything*. (figuratively speaking) – Sideshow Bob Mar 30 '16 at 15:42

1 Answers1

0

This is too long for a comment

You have simpler alternatives: START /BELOWNORMAL <yourexe> can run any arbitrary process at lower priority, w/o modifying the source code.

If you want to do it from within the app, a much better alternative is to us a Job object. Use the JOBOBJECT_CPU_RATE_CONTROL_INFORMATION for fine grained control of how much CPU your app can consume. The most important benefit of JOBs vs. thread affinity is that job restrictions apply to the entire process and to any process spawned by the controlled process.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569