Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a multi-threaded program, with a shared hash data structure. One thread will add elements to the hash, and the other will occasinally delete them. I'm assuming adding an element is an 'atomic operation', but is deleting them 'atomic' as well? If neither is atomic, any suggestions on locking the data structure or element for the moment it is assigned/deleted?

Replies are listed 'Best First'.
Re: Deleting Hash Elements
by andyf (Pilgrim) on May 19, 2004 at 15:40 UTC
    Perhaps you could Tie it to a filehandle and use flock? I'm going to stick my neck out and guess delete is atomic and thread safe. Just as a philosophy pointer - design something to break your program, there's nothing like empirical destructive stress testing to get the answer. Write a couple of very impolite thread loops to compete over a hash and set it running for a few hundred thousand cycles, see if any collisions occur.
    BOL.
    Andy.

    Update: I found this for you.
    hash util
Re: Deleting Hash Elements
by BrowserUk (Patriarch) on May 20, 2004 at 03:20 UTC

    If you are sharing the hash using either the :shared attribute or the share() function from threads::shared (which is the correct way to do things), then you should be using the lock() function (also from threads::shared) to interlock around accesses to the shared data.

    I think that using either a file lock, or Hash::Util for this purpose is dubious.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: Deleting Hash Elements
by Anonymous Monk on May 19, 2004 at 16:15 UTC
    Thanks! That should be just what I need. The Hash::Util is quite nice :)
Re: Deleting Hash Elements
by graff (Chancellor) on May 20, 2004 at 02:32 UTC
    I think that race conditions among the threads might be avoided more safely using a semaphore file, which is separate from the actual data that you're manipulating. I posted a handy module drawn from an excellent article in TPJ by Sean Burke on this subject -- the code is here, and the commentary includes a reference to the article.

    (update: then again, since I haven't yet looked closely at the docs for Hash::Util, maybe that module covers the matter well enough. If so, it might be more efficient -- or might be worth benchmarking, if your deletion code ends up consuming a lot of run-time.)