Using GCD and Code Reuse: Avoiding Deadlock in Re-Login Mode

I use GCD to add thread safety to the class.

Some of the public methods of my class are called by other public methods in the class. However, this leads to the problem of blocking re-entry: if I protect the corresponding public methods with synchronous GCD blocks (in some cases), the reuse tool sometimes I try to start the synchronous block of anthers in the current queue, which leads to a deadlock.

What is the most elegant solution? The obvious approach is to have internal versions of the corresponding methods without any GCD blocks and external publicly accessible versions of the method in which GCD blocks wrap calls to the interaction methods. This is not entirely clear to me.

+4
source share
2 answers

Here are a few thoughts:

  • See if you can use immutable objects. This means that whenever a method changes an object, it actually returns a new object with a changed state. Then the blocks will continue and will use this new object. It is simple, does not require special care, but is not always possible.

  • See if your public methods can use private methods that carry state. Since each block will carry around its own internal state, then you are also thread safe.

If you had a use case, this may lead to more ideas coming up ...

0
source

I used a template like this very successfully in our C ++ classes that use send queues for synchronization:

class Foo { public: void doSomething() { dispatch_sync(fQueue, ^{ doSomething_sync(); }); } private: void doSomething_sync() { ... } private: dispatch_queue_t fQueue; }; 

The general convention here is that for any given _sync method in a class, you only call other _sync methods, and not their public counterpart, not _sync .

0
source

All Articles