dispatch_barrier_sync always deadlocks
<p>Given the following snippet of code:</p>

<pre><code>#import &lt;XCTest/XCTest.h&gt;

@interface DispatchTests : XCTestCase {
    dispatch_queue_t _workQueue;
    dispatch_queue_t _readWriteQueue;
    int _value;
}
-(void)read;
-(void)write;
@end

@implementation DispatchTests

-(void)testDispatch {
    _workQueue = dispatch_queue_create("com.work", DISPATCH_QUEUE_CONCURRENT);
    _readWriteQueue = dispatch_queue_create("com.readwrite", DISPATCH_QUEUE_CONCURRENT);
    _value = 0;
    for(int i = 0; i &lt; 100; i++) {
        dispatch_async(_workQueue, ^{
            if(arc4random() % 4 == 0) {
                [self write];
            } else {
                [self read];
            }
        });
    }
    XCTestExpectation* expectation = [self expectationWithDescription:@"dude"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [expectation fulfill];
    });

    [self waitForExpectationsWithTimeout:6.0 handler:nil];
}

-(void)read {
    dispatch_sync(_readWriteQueue, ^{
        NSLog(@"read:%d", _value);
    });
}

-(void)write {
    dispatch_barrier_sync(_readWriteQueue, ^{
        _value++;
        NSLog(@"write:%d", _value);
    });
}

@end
</code></pre>

<p>The purpose of this test is to see if I can use a <code>dispatch_barrier</code> to manage a read/write lock.  In this test, both the reader and writer are synchronous.  The test seems to work fine when I make the barrier asynchronous, however I would like to avoid asynchronous behavior because this implementation is non-trivial.</p>

<p>I'm trying to understand why the <code>write</code> method is deadlocking.  According to the GCD docs:</p>

<blockquote>
  <p>When the barrier block reaches the front of a private concurrent
  queue, it is not executed immediately. Instead, the queue waits until
  its currently executing blocks finish executing. At that point, the
  queue executes the barrier block by itself. Any blocks submitted after
  the barrier block are not executed until the barrier block completes.</p>
</blockquote>

<p>I'm confused by what is meant by "currently executing blocks".</p>

<p>My interpretation is this scenario where a bunch of reads (x) get submitted, then a write (y), then more reads (z):</p>

<ul>
<li>(x) executes</li>
<li>(y) waits until (x) are done</li>
<li>(y) blocks (z) from executing</li>
<li>(x) completes</li>
<li>(y) executes</li>
<li>(y) completes</li>
<li>(z) executes</li>
<li>(z) completes</li>
</ul>