The < 65 observation immediately makes me think you're hitting the queue width limit, which is undocumented (for good reason), but widely understood to be 64. A while back, I wrote a very detailed answer about this queue width limit over here. You should check it out.
I do have some relevant ideas I can share:
The first thing I would recommend would be replacing the print()
calls with something that does not trigger I/O. You could create a numReads
variable and a numWrites
variable, and then use something like an atomic compare and swap operation to increment them, then read them after the loop completes and make sure they're what you expected. See Swift Atomics over here. You could also just dispatch the print operations (async) to the main queue. That would also eliminate any I/O problems.
I'll also note here that by introducing a barrier
block on every single iteration of the outer for
loop, you're effectively making that queue serial, but with a non-deterministic order. At the very least, you're creating a ton of contention for it, which is suboptimal. Reader/Writer locks tend to make the most sense when there are many more reads than writes, but your code here has a 1:1 ratio of reads to writes. If that is what your real use case looks like, you should just use a serial queue (or a mutex) since it would achieve the same effect, but without the contention.
At the risk of being "that guy", can you maybe elaborate on what you're trying to accomplish here? If you're just trying to prove to yourself that reader/writer locks emulated using barrier blocks work, I can assure you that they do.