Could anyone explain how InterProcessLock works?

I think I know how to use it, just looking for a better understanding.

Like right now, I have a save file function, and looks something like

    const InterProcessLock::ScopedLockType sl (saveLock);
    
    saveFile.deleteFile();
    FileOutputStream os(saveFile);
    dataTree.writeToStream(os);

and in the header

private:
InterProcessLock saveLock{"saveLock"};

How does interProcessLock/ scopedLock even know what to lock down?
And I guess while were here is this related to criticalSections ? I also don’t quite understand what the criticalSection is/does.

Any input appreciated! Thanks.

It doesn’t. You tell it, by using it in the scope where its needed. Taking the lock means any other code requesting it will have to wait until you’ve released it - so, be careful with the scope where you apply the lock, and be sure to only do ‘critical’ things while you are holding the lock.

criticalSections are kind of important. You should probably get familiar with the basics … they are also critical areas of the code that you must protect from re-entry - with a lock, for example (but its not the only way to protect critical sections - see also semaphores and mutexes). Therefore they are related to your understanding of the ScopedLock, too - you should definitely try to understand the ways that scoped code should be treated, critically …

Instead of locking you could use the juce::TemporaryFile.
You write to a unique temporary sibling and once you are done it is moved as an atomic filesystem call into it’s place by calling overwriteTargetFileWithTemporary().

Make sure to respect the warnings in the linked function:

Before calling this, make sure:

  • that you’ve actually written to the temporary file
  • that you’ve closed any open streams that you were using to write to it
  • and that you don’t have any streams open to the target file, which would prevent it being overwritten

The InterProcessLock is platform dependant and I think often implemented on the filesystem similar to pid files.