python - OpenMP中有没有类似Python的threading.Event的机制?

标签 python c openmp

我正在尝试制作一个解决方案列表,以在 C 中实现 Python 的 threading.Event [1] 的功能。

通常,当线程之间需要同步时,第一个使用/解释的机制是锁(也称为互斥)。 Python 的 threading.Event 类是另一种同步机制,可用于自动阻塞线程,直到特定条件为真。

使用 pthread 我认为可以使用条件变量属性 [2] 来做到这一点。

关于omp,这可能吗?基于 python 中发生的事情,我用 虚构的 类型 EventEventsQueue 编写了以下示例:

int nthreads;
Event *evt;
EventsQueue *queue;

#pragma omp parallel private(evt)
{
    #pragma omp single
    {
        nthreads = omp_get_num_threads()-1;
    }
    if (!omp_get_thread_num()) /*master thread*/
    {
        while (nthreads)
        {
            evt = events_queue_pop(queue);
            evt_set(evt);
        }
    }
    else                       /*other threads */
    {
        evt = alloc_event();
        events_queue_append(queue, evt);
        /* each threads waits for master thread to set its event*/
        evt_wait(evt);
        free_event(evt);
        #pragma omp critical
        {
            nthreads--;
        }
    }
}

如您所见,我可以使用 #pragma omp critical 获得与 Python 的 threading.Lock 类似的效果(在示例中我保护 nthreads用它)。问题是 threading.Event。对于 OpenMP,我找不到类似的东西。

[1] http://docs.python.org/2/library/threading.html#event-objects

[2] http://www.cs.cf.ac.uk/Dave/C/node31.html#SECTION003120000000000000000

最佳答案

注意:此解决方案不正确。查看此答案末尾的编辑。

嗯...我想我已经找到了如何去做。查看Python的线程模块[1]的源码,其实看起来很简单。

这是保持 FIFO可重入锁(在 OpenMP 中实现为 omp_nest_lock_t)的问题。每当 Event.wait([timeout]) 被调用时,一个新的锁被附加到 FIFO 并立即获取两次(第二次时间将阻塞,直到第一个被释放!)。 然后,当 Event.set() 被调用时,FIFO 中的所有锁都会被释放并从中移除。

我希望这个答案对以后遇到这个问题的任何人都有用。

[1] http://svn.python.org/projects/python/branches/py3k/Lib/threading.py

编辑:我发现一篇文章说这个解决方案不正确并讨论了这个问题:

[2] http://www.michaelsuess.net/publications/wirz_suess_leopold_taskpools_06.pdf

关于python - OpenMP中有没有类似Python的threading.Event的机制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15649100/

相关文章:

c - 字节似乎被转移了

c - 将值分配给结构数组中的变量

c - 我自己的 C Linux Shell 中的环境变量?

c++ - MPI 与 OpenMP 的性能比较

c - OpenMP 有序子句

python - vscode远程容器中的自动完成python

python - 编译后的 Python 代码和 C++ 代码一样快吗?

Python:Flask 缓存无法在特定时间范围内工作

python - 使用 map /缩小的反向列表

C、OpenMP : How can I make this parallisation of a triple loop better?