I have long wanted to know if it is possible to do the following for unit testing:

Is it possible to add a method to NSThread that will show whether a given thread is blocked (stopped) or not?

I assume that if this problem is solved in principle, it would be convenient to make a separate category NSThread + IsBlocked, containing this method and quite worthy of its own separate repository on Github;)

Right now I am doing NSCondition - here is the call chain that makes [NSCondition wait] to stop a thread:

[NSCondition wait] pthread_cond_wait$UNIX2003 _pthread_cond_wait __psynch_cvwait 

In addition to NSCondition, there are many other ways to block / stop NSThread threads: dispatch semaphores, NSConditionLock, [NSThread sleepForTimeInterval:], etc. - I know Objective-C only at the level of an iOS developer, so I have no idea whether it is possible to write such a method that will show the fact of blocking the flow for all these methods at once. I would even appreciate a method that works only with NSCondition and __psynch_cvwait.

Here is a simple example of what I would like to achieve (the desired method is isBlocked ):

 // Some test case // ... __block NSThread *thread; NSCondition *condition = [NSCondition alloc] init]; dispatch_async(someQueue(), ^{ thread = NSThread.currentThread; [condition lock]; [condition wait]; [condition unlock]; }); while(1) { NSLog(@"Thread is blocked: %d", thread.isBlocked); } 

I am not a connoisseur of pure C and POSIX threads, so if you know the answer, please make it detailed.

Note: we are talking about blocking (stopping) the stream, and not about checking isLocked, like, "Are we located @synchronized {}?"

  • In my opinion, in well-written code, this method is not needed and even harmful. Moreover, at what point in time the obtained value is valid? - VladD pm
  • one
    @VladD, that's right. I asked the question mainly for (self) education: At some point I wondered if it was possible in principle to solve this problem. Actually I am going to use the received solution only in 1-2 exceptional particular cases. I hope that the fact that such a question is asked will not inspire people to move in the wrong direction, and let these comments additionally serve to prevent this from happening! - Stanislav Pankevich

1 answer 1

World - Russia 1: 0 - the answer was received in the topic, which, in parallel with this, was opened by me on SO: Is it possible to check if an NSThread is blocked? .

There see the accepted answer. Very elegant solution for NSCondition.

At the same time showing how you can beautifully modify the behavior of classes, replacing the methods with each other (according to logic, it remotely resembles alias_method_chain in Ruby).