Solved

Best way to control multiple threads writing & reading from the same file (Perl)

Posted on 2010-11-27
1
220 Views
Last Modified: 2012-05-10
Expertos,

What's the best way to control multiple threads writing & reading from the same file in Perl?

I'm working with the threads::simple module.

Thanks!

0
Comment
Question by:php-newbie
1 Comment
 
LVL 16

Accepted Solution

by:
jmatix earned 500 total points
ID: 34230935
You can use flock() to lock a file handle in exclusive or shared mode. So each thread can call flock() to acquire an exclusive lock before writing to the file and immediately release the lock so that other threads also can obtain a lock and write to the file. Here is the sample from the documentation (http://perldoc.perl.org/functions/flock.html):



use Fcntl ':flock'; # import LOCK_* constants



sub lock {

    flock(MBOX,LOCK_EX);

    # and, in case someone appended

    # while we were waiting...

    seek(MBOX, 0, 2);

}



sub unlock {

    flock(MBOX,LOCK_UN);

}



open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")

        or die "Can't open mailbox: $!";



lock();

print MBOX $msg,"\n\n";

unlock();

Open in new window

0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sort hash by values desc 2 176
Perl - Mawk 2 69
Writing a parser for java language 4 61
Perl Write to Specific line in a file 15 52
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now