缺少OpenMP功能:线程优先级

时间:2009-03-23 00:30:27

标签: multithreading openmp thread-priority

任何人都会想到它。 OpenMP功能可以调整cpu肌肉来处理哑铃。在我对openmp的研究中,我们无法设置线程优先级来执行具有强大功能的块代码。只有一种方式(_beginthreadex或带有5.参数的CreateThread函数)来创建具有最高优先级的线程。

此问题的一些代码:

这是手动设置。

int numberOfCore = ( execute __cpuid to obtain number of cores on your cpu ).

HANDLES* hThreads = new HANDLES[ numberOfCore ];
hThreads[0] = _beginthreadex( NULL, 0, someThreadFunc, NULL, 0, NULL );

SetThreadPriority( hThreads[0], HIGH_PRIORITY_CLASS );

WaitForMultipleObjects(...); 

我希望看到这一部分:

#pragma omp parallel
{
#pragma omp for ( threadpriority:HIGH_PRIORITY_CLASS )
 for( ;; ) { ... }
}

#pragma omp parallel
{
// Generally this function greatly appreciativable.
_omp_set_priority( HIGH_PRIORITY_CLASS );
#pragma omp for
 for( ;; ) { ... }
}

我不知道是否有办法通过openmp请设置优先级请告知我们。

2 个答案:

答案 0 :(得分:3)

您可以在循环体中执行SetThreadPriority,而无需OpenMP的特殊支持:

for (...)
{
  DWORD priority=GetThreadPriority(...);
  SetThreadPriority(...);
  // stuff
  SetThreadPriority(priority);
}

答案 1 :(得分:1)

简单测试显示意外结果: 我在Visual Studio 2010(Windows 7)中运行了一个简单的测试:

    #include <stdio.h>
    #include <omp.h>
    #include <windows.h>

    int main()
    {
        int tid, nthreads;

        SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);

        #pragma omp parallel private(tid) num_threads(4)
        {
            tid = omp_get_thread_num();
            printf("Thread %d: Priority = %d\n", tid, GetThreadPriority(GetCurrentThread()));
        }

        printf("\n");

        #pragma omp parallel private(tid) shared(nthreads) num_threads(4)
        {
            tid = omp_get_thread_num();

            #pragma omp master
            {
                printf("Master Thread %d: Priority = %d\n", tid, GetThreadPriority(GetCurrentThread()));
            }
        }

        #pragma omp parallel num_threads(4)
        {
            SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
        }

        printf("\n");

        #pragma omp parallel private(tid) num_threads(4)
        {
            tid = omp_get_thread_num();
            printf("Thread %d: Priority = %d\n", tid, GetThreadPriority(GetCurrentThread()));
        }

        return 0;
    }

输出结果为:

    Thread 1: Priority = 0
    Thread 0: Priority = 1
    Thread 2: Priority = 0
    Thread 3: Priority = 0

    Master Thread 0: Priority = 1

    Thread 0: Priority = 1
    Thread 1: Priority = 1
    Thread 3: Priority = 1
    Thread 2: Priority = 1

说明: 使用main的线程优先级执行OpenMP主线程。 其他OpenMP线程保留在Normal优先级。 手动设置OpenMP线程的线程优先级时,线程保持该优先级。