Wednesday, May 11, 2011

How to Use Thread Locking in Perl

Thread Locking in Perl

Thread locking is used to prevent "race conditions" when multiple threads try to access or modify the same shared resource (like a variable, a file, or a database record) at the exact same time. By locking a shared variable, you force other threads to wait in line until the current thread is finished with it.


use strict;
use warnings;
use threads;
use threads::shared;

# Declare a shared variable to act as a semaphore/lock across all threads
my $sem :shared;

# A thread-safe print function
sub tprint {
    # Get the ID of the currently executing thread
    my $tid = threads->tid; 
    
    # Lock the shared variable. If another thread already has the lock, 
    # this thread will pause here and wait until it is released.
    lock $sem; 
    
    # Safely print the thread ID and the provided arguments
    print "$tid: ", @_, "\n";
    
    # The lock is automatically released when the variable goes out of scope 
    # at the end of this block.
}

# A thread-safe warning function
sub twarn {
    my $tid = threads->tid;
    
    # Lock the shared variable to prevent warning messages from different 
    # threads from overlapping or scrambling together on the screen.
    lock $sem; 
    
    warn "$tid: ", @_;
}

No comments: