Idea for Threads
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Sun May 13 10:19:28 PDT 2007
Martin Persenius wrote:
> 1. Before reading, check if it is locked, then wait or read.
> 2. Before writing, acquire lock, write, release.
That's not safe, there's a race condition.
Thread A: Check if locked, begin reading.
>>> thread switch <<<
Thread B: Acquire lock, write, release.
>>> thread switch <<<
Thread A: Continue reading.
Thread A will still have the stuff being read changing from under it...
The writing procedure needs to be modified to check if anyone's
currently reading and, if so, wait until they're done.
This means the readers also need to mark something while they're busy.
It'd have to be some kind of counter since multiple simultaneous readers
are allowed.
If you want new readers to wait until a waiting writer has done it's
thing the readers also need to actually lock something, though perhaps
only at the beginning and end, not while they're working.
Some googling reveals that pthreads has pthread_rwlock* to implement
this[1].
[1]: See
http://www.die.net/doc/linux/man/man3/pthread_rwlock_init.3.html and
related pages.
More information about the Digitalmars-d
mailing list