0

我正在将 cpp 代码移植到 Objective C。我是这个编程的新手。

我必须启动一个线程,该线程正在调用一个名为 timeoutThread 的函数。在一个名为 insert() 的函数中,他们使用 setEvent(m_Thread) 设置事件,在函数 timeoutThread 中,他们通过调用 waitforsingleobject(m_thread,延迟)。在 waitforsingleObject 的正上方,他们通过 setEvent(m_ThreadEvent) 设置另一个事件。并在超时线程函数中做其他事情。我已经创建了一个 NSOperationQueue 并使用 initWithTarget:toTarget:object 调用了该函数。但是我如何设置事件并像它们在 Objective C 的 cpp 中所做的一样通知。

通过一个简单的例子对此进行任何解释对于像我这样的初学者来说都是非常有帮助的。

4

1 回答 1

1

I admit not to being entirely up on the Windows way of doing these things, but I imagine the primitive you want if you're waiting on single flags only is NSConditionLock. Each condition lock has a particular condition, threads can attempt to lock it with no regard for the condition or only when it has a particular condition, optionally with a timeout for both. They can then unlock and, optionally, set a new condition when they do so.

Possibly a more straightforward approach is to create your NSThreads manually rather than just offloading operations into an NSOperationQueue. Each NSThread automatically has an NSRunloop so you can then use semantics like:

[object performSelector:@selector(operation:) onThread:targetThread withObject:someArgumentForOperation waitUntilDone:NO];

In which case the method 'operation:' will be called with the nominated argument on the nominated thread as soon as an opportunity arises, and the calling thread isn't blocked. Runloops solve the same problem as the classic win32 message dispatch mechanisms but invert responsibility — Cocoa deals with blocking threads, waking upon messages and issuing the appropriate function calls.

于 2011-05-25T15:22:44.460 回答