467,923 Members | 1,540 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,923 developers. It's quick & easy.

Locking Threads & Preventing Race Conditions

I've been trying to find a suitable method for preventing race conditions in my own code.

Currently I'm using a file and the flock function to prevent code in other threads from executing at the same time.

For example:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $pointer = fopen ('./thread.lock', 'a+');
  4. flock ($pointer, LOCK_EX);
  6. // Code from here on in other threads cannot run at the same time.
  8. flock ($pointer, LOCK_UN);
  10. fclose ($pointer);
  11. ?>
At the comment I would do something like query the database for information, then write a new value, and using the code before and after would ensure that race conditions wouldn't occur, and some other thread running wouldn't update the data in the database after this thread read the data, and before it wrote the new value (which would be very rare anyways).

The problem I'm having is flock seems to have, within itself, it's own problem with race conditions. If multiple attempts to lock a file are made at the same time, the server crashes.

I know there's a better solution out there, but I'm a little puzzled on where to look.

I have tried a similar setup with my current method like this, but it, even though less likely to crash the server, still has issues with too many requests at one time.

Expand|Select|Wrap|Line Numbers
  1. while (!flock ($pointer, LOCK_EX | LOCK_NB))
  2. {
  3. usleep (100000);
  4. }
Jul 5 '09 #1
  • viewed: 1487

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

12 posts views Thread by Alban Hertroys | last post: by
13 posts views Thread by Jeff Davis | last post: by
18 posts views Thread by jess.austin | last post: by
35 posts views Thread by Carl J. Van Arsdall | last post: by
5 posts views Thread by Chris Mullins | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.