2

我有两个线程作为生产者,消费者。在生产者线程中,我有以下代码:

{
    mediaQueue->PushEvent( boost::bind(/* params are not important */) );

    return 0;
}

mediaQueue 是一个消息队列,在 PushEvent() 调用中通知线程有要处理的作业。消费者线程只是执行函子,由绑定创建。

对我来说,生产者线程在消费者线程执行函子之前返回非常重要。

所以问题是:生产者是否有可能在它推送事件之后但在它返回之前被中断?

到目前为止,我的研究让我认为这是可能的,我应该实施 lock,但您对此有何看法?

4

2 回答 2

3

The scheduler can interrupt your thread at any time. It doesn't (necessarily) know or care what your thread is doing when its time is up. If there's a possible race condition, yes, you must take the time and effort to implement correct locking.

In your case, it's easy enough. Just wait on an object that's set in the callee function on return from your PushEvent function.

于 2012-05-04T08:48:44.833 回答
1

Yes, it's possible. A thread can be descheduled pretty much any time.

It sounds like there's something wrong though, if it matters when the statement return 0; is executed. Is it really the return that has to execute before the functor, or is it something else that the producer thread does?

于 2012-05-04T08:49:58.643 回答