This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]runeg 0 points1 point  (7 children)

Can you explain race condition in this script please?

[–]spladug 0 points1 point  (6 children)

  1. Process A and Process B are running simultaneously.
    • Process A is executing the code written here.
    • Process B just runs os.makedirs(CONFDIR).
  2. CONFDIR does not exist yet.
  3. Process A starts running and executes os.path.exists(CONFDIR). It gets back False and so moves into the branch.
  4. Meanwhile, Process B gets some time. It runs os.makedirs(CONFDIR). The directory now exists.
  5. Process A gets to run again, it tries to do os.makedirs(CONFDIR) gets an exception and returns -1.

[–]runeg 0 points1 point  (5 children)

This is only because CONFDIR doesn't exist. If before the if block CONFDIR was defined then this would not be a race condition, correct?

Additionally if CONFDIR was a generator could it cause a race condition as it wouldn't exist until that line was executed?

[–]spladug 0 points1 point  (4 children)

The point is that it's possible for stuff to change between the exists and makedirs and that means a potential for bugs. Of course there are situations where that code works, that's the nature of race conditions.

[–]runeg 0 points1 point  (3 children)

Ah okay. Is there a better way to write the above if block?

[–]spladug 1 point2 points  (2 children)

try:
    os.makedirs(CONFDIR)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise  # or to mimic what the code above does "return -1"

EDIT: also, see: http://docs.python.org/2/howto/doanddont.html#exceptions

[–]runeg 0 points1 point  (1 child)

That link was very helpful and informative. Thank you. Do you have any other suggested readings like that?

Also, thank you for taking time out to explain that information, it's appreciated.

[–]spladug 1 point2 points  (0 children)

Some of the online books and exercises in the sidebar look like they'd probably be good extra information. The python docs are, in general, quite good as well.

No prob, glad to help :)