小编典典

Linux中使用条件变量执行Windows事件?

linux

我正在尝试在Linux中实现非常简单的Windows事件。仅针对我的情况-3个线程,1个主线程和2个辅助线程。每个辅助线程通过SetEvent引发1个事件,主线程等待它。例:

int main()
{
    void* Events[2];
    Events[0] = CreateEvent();
    Events[1] = CreateEvent();

    pthread_start(Thread, Events[0]);
    pthread_start(Thread, Events[1]);

    WaitForMultipleObjects(2, Events, 30000) // 30 seconds timeout

    return 0;
}

int* thread(void* Event)
{
    // Do something
    SetEvent(Event);
    // Do something
}

因此,要实现它,我使用条件变量。但是我的问题是-这是正确的方法吗?还是我做错了什么?我的实现:

// Actually, this function return pointer to struct with mutex and cond
// here i just simplified example
void* CreateEvent(mutex, condition)
{
    pthread_mutex_init(mutex, NULL);
    pthread_cond_init(condition, NULL);
}

bool SetEvent (mutex, condition)
{
    pthread_mutex_lock(mutex);
    pthread_cond_signal(condition);
    pthread_mutex_unlock(mutex);
}

int WaitForSingleObject(mutex, condition, timeout)
{
    pthread_mutex_lock(mutex);
    pthread_cond_timedwait(condition, mutex, timeout);
    pthread_mutex_unlock(mutex);
}

// Call WaitForSingleObject for each event. 
// Yes, i know, that its a wrong way, but it should work in my example.
int WaitForMultipleObjects(count, mutex[], condition[], timeout);

一切似乎都很好,但是我认为,当我在辅助线程中的SetEvent被调用之前,在主线程中调用WaitFor
..函数时,将出现该问题。在Windows中,它运作良好,但在Linux中,上面仅描述了想法。

也许您告诉我解决这个问题的更好方法?谢谢。

UPD: 超时非常重要,因为辅助线程之一可能无法传递SetEvent()。


阅读 449

收藏
2020-06-07

共1个答案

小编典典

已经有关于stackoverflow的类似问题:Linux中的WaitForSingleObject和WaitForMultipleObjects等效项

另外,您可以使用信号量:

sem_t semOne  ;
sem_t semTwo  ;
sem_t semMain ;

在主线程中:

sem_init(semOne,0,0) ;
sem_init(semTwo,0,0) ;
sem_init(semMain,0,0) ;

...


sem_wait(&semMain);

// Thread 1
sem_wait(&semOne);
sem_post(&semMain);


// Thread 2
sem_wait(&semTwo);
sem_post(&semMain);

可以在这里找到详细的描述和各种示例:------
http://www.ibm.com/developerworks/linux/library/l-ipc2lin3/index.html

以前的链接不再可用。Internet存档的Wayback
Machine上的最新存档版本是:https
://web.archive.org/web/20130515223326/http:
//www.ibm.com/developerworks/linux/library/l-ipc2lin3/index.html

2020-06-07