2

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?

whisperstream
  • 1,897
  • 3
  • 20
  • 25
  • There are about 20 ways (ok, maybe an exaggeration, but a half-dozen) to send a timer event of some sort to a thread. But the most important thing to know is that the main thread should never wait. – Hot Licks May 23 '12 at 03:52

1 Answers1

5

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]
whisperstream
  • 1,897
  • 3
  • 20
  • 25