1

I'm maintaining some software that runs on Windows and several UNIX platforms: Mac, Linux, AIX and Solaris. It implements a threading infrastructure on top of pthreads or Win32 threads. I'm starting to implement rwlocks in this infrastructure so that our developers can use them. So far, so good.

On Mac OS X, we originally implemented threading using normal pthreads, but found that performance was very poor, because OS X pthreads mutexes always made system calls. Apple recommended that we use GCD dispatch semaphores, and this worked just fine, with a considerable performance improvement, because waiting for a semaphore is a simple userspace operation if the semaphore is free.

However, I can't see any way to do the equivalent of rwlocks, and it looks impossible in terms of a simple semaphore. Am I missing something, or is this actually impossible?

Note: switching everything to the GCD approach with queues and blocks is not feasible. The code has to work on platforms that don't have GCD, and re-writing all the usages of the threading infrastructure, in about 170 source files, would not be practical.

John Dallman
  • 590
  • 4
  • 18
  • The usual approach to implement read-write locks in GCD is described [in this answer](http://stackoverflow.com/a/10234838/1218876) (and the related links). Is there a reason why you can't use that method? Why do you need to use exactly a single semaphore, and nothing else? – Kurt Revis Jul 19 '16 at 06:38
  • I can happily use multiple semaphores, if I can find a way to do it, but as far as I can see I can't use dispatch_barrier_async(), because I can't use Apple's block construct. I'm working in a domain-specific language which compiles to C, and it knows nothing about Apple's blocks. The *only* part of GCD that I'm using is the semaphores: everything else is pthreads. – John Dallman Jul 19 '16 at 09:40
  • You don't necessarily need to use blocks. GCD has function-based versions of all of its primitives. For instance there's [dispatch_barrier_async_f](https://developer.apple.com/reference/dispatch/1452812-dispatch_barrier_async_f). – Kurt Revis Jul 20 '16 at 03:54
  • Thanks for that, Kurt. It does not help especially with the current problem, but it's worth knowing. – John Dallman Jul 20 '16 at 09:30

1 Answers1

0

Silly me, should have checked Wikipedia first. There are several ways to do it there. It is a standard computer science problem: not totally trivial, but well-understood.

John Dallman
  • 590
  • 4
  • 18