我正在使用 GCD 为类添加线程安全性。
我的类的一些公共方法被类中的其他公共方法调用。但是,这会导致重入锁定问题:如果我使用同步 GCD 块(在某些情况下)保护适当的公开可见方法,则重用意味着有时我会尝试在当前队列上运行另一个同步块,从而导致死锁。
什么是最优雅的解决方案?一个明显的方法是拥有适当方法的内部版本,没有任何 GCD 块,以及具有 GCD 块包装对内部方法的调用的方法的外部公共版本。这对我来说不太合适。
我正在使用 GCD 为类添加线程安全性。
我的类的一些公共方法被类中的其他公共方法调用。但是,这会导致重入锁定问题:如果我使用同步 GCD 块(在某些情况下)保护适当的公开可见方法,则重用意味着有时我会尝试在当前队列上运行另一个同步块,从而导致死锁。
什么是最优雅的解决方案?一个明显的方法是拥有适当方法的内部版本,没有任何 GCD 块,以及具有 GCD 块包装对内部方法的调用的方法的外部公共版本。这对我来说不太合适。
Here are a few thoughts:
See if you can't use immutable objects. This means that whenever a method would modify the object it actually returns a new object with the modified state. The blocks would then go on and use this new object. This is simple, requires no special care but is not always possible.
See if your public methods can't use private methods that carry around state. Since each block would carry around its own internal state then you are also thread safe.
If you had some example use case it might lead to a more ideas...
我在使用调度队列进行同步的 C++ 类中非常成功地使用了这样的模式:
class Foo
{
public:
void doSomething() {
dispatch_sync(fQueue, ^{ doSomething_sync(); });
}
private:
void doSomething_sync() { ... }
private:
dispatch_queue_t fQueue;
};
这里的一般约定是,对于_sync
类中的任何给定方法,您只调用其他_sync
方法而不是它们的非_sync
公共对应方法。