Brothers,
I'm seeking wisdom and potentially flashes of inspiration... I have a process that receives files via NDM from an external partner in pairs - a data file and a status file. The files may arrive in any order, and could be anything from minutes apart to fractions of a second. I'm trying to create a process that populates the file content into an Oracle database via a Perl script triggered after each file arrives. Although the files can arrive in pseudo parallel, I need to process them in sequence, so I'm trying to semaphore lock them (IPC::Semaphore). If they arrive separated by, say, 1 second the lock works nicely, but if they arrive a tenth of a second apart, both Perl processes say that they're the first one and create and initialize the semaphore.
$sem = IPC::Semaphore->new( 4321, 1, S_IRUSR | S_IWUSR ); if ( $sem ) { # Semaphore already exists so just open it print "Semaphore already exists - just open it\n"; $sem = IPC::Semaphore->new( 4321, 1, S_IRUSR | S_IWUSR ); } else { # The semaphore didn't already exit so create it print "Create semaphore \n"; $sem = IPC::Semaphore->new( 4321, 1, IPC_CREAT | S_IRUSR | S_IWUSR + ); print "Semaphore created\n"; $sem->setval(0,1); print "Semaphore initialised\n"; } print "Locking other threads\n"; $sem->op(0, -1, SEM_UNDO);
Depending on exact timing, I see that it's possible for the first process to create the semaphore and attempt to lock the other process, but the other one running a fraction behind has not detected the creation so it does its own and sets the semaphore to 1, so revoking it's partner's lock! I can't see a fool proof way of getting around this, so any divine inspiration gratefully received.
Jerry

In reply to Semaphore puzzle by jerryhone

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.