• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 255
  • Last Modified:

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


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.


1 Solution
Justin MathewsCommented:
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 {
    # and, in case someone appended
    # while we were waiting...
    seek(MBOX, 0, 2);

sub unlock {

open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
        or die "Can't open mailbox: $!";

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

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now