Skip to content

Instantly share code, notes, and snippets.

@manwar
Last active March 1, 2025 17:09
RLock in Perl and Python.

-- Back to Index --


A mutex (short for "mutual exclusion") is a synchronization primitive used in threading to prevent multiple threads from accessing shared resources simultaneously, which can lead to race conditions and inconsistent data. It ensures that only one thread can execute a critical section of code at a time.

A re-entrant mutex is a particular type of mutex that can be locked multiple times by the same process or thread.

One interesting difference between the regular lock and Rlock in Python is that the regular lock can be released by different threads than the one that acquired it, but the re-entrant lock must be released by the same thread that acquired it. And of course, it must be released by that thread as many times as it was acquired before it will be available for another thread to take. This is just the difference between how lock and Rlock are implemented in Python.

First implementation in Python:

[Source Code]

#!/usr/bin/env python3

import time
import threading

rlock = threading.RLock()

def worker(id):
    with rlock:
        print(f"Thread: {id} acquired the lock.")
        with rlock:
            print(f"Thread: {id} re-acquired the same lock.")
            time.sleep(1)
        print(f"Thread: {id} released the nested lock.")
    print(f"Thread: {id} released the lock.")

if __name__ == '__main__':
    threading.Thread(target=worker, args=(1,)).start()

See the action now:

$ py rlock.py
Thread: 1 acquired the lock.
Thread: 1 re-acquired the same lock.
Thread: 1 released the nested lock.
Thread: 1 released the lock.
$

Let do the same in Perl now:

[Source Code]

#!/usr/bin/env perl

use v5.38;
use threads;
use threads::shared;

my $rlock :shared = 1;

sub worker {
    my $id = threads->tid();
    lock($rlock);
    say "Thread: $id acquired the lock.";
    {
        say "Thread: $id re-acquired the same lock.";
        lock($rlock);
        sleep(1);
        say "Thread: $id released the nested lock.";
    }
    say "Thread: $id released the lock.";
}

threads->create(\&worker)->join();

Run the script now:

$ perl rlock.pl
Thread: 1 acquired the lock.
Thread: 1 re-acquired the same lock.
Thread: 1 released the nested lock.
Thread: 1 released the lock.
$

-- Back to Index --


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment