How Do You Do File Locking in Raku?

Viewed 160

I've been trying to figure out how to do file locking in Raku without success. I started looking into fcntl with NativeCall, but then realized that fcntl locks don't prevent file access from other threads. What's the best way to do file locking in Raku?

2 Answers

IO::Handle has a lock and an unlock method to lock/unlock files. Locks can be exclusive or shared.

I've come across these Raku-idiomatic phrases and use them a lot, with 'given' topicalizing for brevity/clarity:

Read:

    given $path.IO.open {
        .lock: :shared;
        %data = from-json(.slurp);
        .close;
    }

Write:

    given $path.IO.open(:w) {
        .lock;
        .spurt: to-json(%data);
        .close;
    }
Related