gpt4 book ai didi

multithreading - 如何检测 TEvent 已被设置?

转载 作者:行者123 更新时间:2023-12-03 14:41:44 41 4
gpt4 key购买 nike

Delphi XE2 文档这样描述 TEvent:

Sometimes, you need to wait for a thread to finish some operation rather than waiting for a particular thread to complete execution. To do this, use an event object. Event objects (System.SyncObjs.TEvent) should be created with global scope so that they can act like signals that are visible to all threads.

When a thread completes an operation that other threads depend on, it calls TEvent.SetEvent. SetEvent turns on the signal, so any other thread that checks will know that the operation has completed. To turn off the signal, use the ResetEvent method.

For example, consider a situation where you must wait for several threads to complete their execution rather than a single thread. Because you don't know which thread will finish last, you can't simply use the WaitFor method of one of the threads. Instead, you can have each thread increment a counter when it is finished, and have the last thread signal that they are all done by setting an event.

但是,Delphi 文档没有解释另一个线程如何检测 TEvent.Set 事件被调用。您能否解释一下如何检查 TEvent.Set 是否被调用?

最佳答案

如果您想测试事件是否已发出信号,请调用 WaitFor 方法并传递超时值0。如果设置了事件,它将返回 wrSignaled 。如果没有,会立即超时并返回wrTimeout .

话虽如此,事件的正常用法不是检查它是否以这种方式发出信号,而是通过阻塞当前线程直到事件发出信号来进行同步。您可以通过将非零值传递给超时参数(常数 INFINITE)来完成此操作。如果您确定它会完成并且想要等到它完成,或者如果您不想无限期地阻塞,则使用较小的值。

关于multithreading - 如何检测 TEvent 已被设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993041/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com