How do I wake up a thread at a specified time in objective-c

1.9k views Asked by At

I'm writing an ssh wrapper in objective-c, I'm trying to implement a maxTime a command should take to execute. The way I implement it is:

Main Thread:

  1. calculate timeout
  2. create asyncThread (GCD queue) to execute command and parse the returned data
  3. waitForTimeoutOrSignal
  4. return result

AsyncThread:

  1. execute command
  2. get returned data
  3. if received correct data signal MainThread

In C# I had good success using ManualResetEvents to signal the MainThread. In Objective-C the closest class I can find is NSCondition but it seems that it's not built for inter-thread communication.

In fact I get:

2012-05-22 00:31:05.761 libssh2-for-iOS[60821:11303] ** -[NSCondition unlock]: condition ( '(null)') unlocked from thread which did not lock it

2012-05-22 00:31:05.763 libssh2-for-iOS[60821:11303] ** Break on _NSLockError() to debug.

when I try to use it. Is there another way to use NSCondition or a better way for a thread to sleep until it receives some sort of signal?

1

There are 1 answers

2
whisperstream On BEST ANSWER

Ok turns out that I was almost right. My problem (as the compiler handily alluded to) was that I was locking in one thread and unlocking in another. What really solved it was learning about the "signal" method in NSCondition. So now I've rewritten the code thusly:

Worker #1 Thread:

[NSCondition lock]
start worker thread
if([NSCondition waitUntil:maxTime])
    // got signal
else
    // timed out
[NSCondition unlock]

Worker #2 Thread:

Do work
[NSCondition signal]