By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,885 Members | 1,072 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,885 IT Pros & Developers. It's quick & easy.

Locking Threads & Preventing Race Conditions

P: 65
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
Share this question for a faster answer!
Share on Google+

Post your reply

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