FCF 2.0 development in progress...
> > > >
[News] [Packages API] [Downloads] [Donate to the project] [Contacts]

fcf.NLock.lockNamedMutex() function

[SERVER ONLY] fcf.NLock.lockNamedMutex(string a_name, function a_cb)

Package: fcf-framework-lock

File: fcf-framework-lock:index.js

Available from version: 1.0.6

Performs a lock on a named mutex

Arguments

string a_name
- The mutex name

function a_cb
- The function of processing the result of the function execution.

Function signature: a_cb(Error|undefined a_error, number a_lock)

  • Error|undefined a_error - If the function executed with an error, then the argument contains an error object

  • number a_lock - Contains a lock handle to be passed to the fcf.NLock.unlockNamedMutex function to unlock the mutex.

Example: Function application

Below is an example of implementing a critical section using named mutexes. The output to the terminal is made for two instance of the program running simultaneously.

let libLock = require("fcf-framework-lock"); async function main(){ const mutexName = "TestMutexForExample" console.log(`PID:${process.pid}: ${new Date().toISOString()}: "Wait locking ..."`); let lock = await new Promise((a_res, a_rej)=>{ libLock.lockNamedMutex(mutexName, (a_error, a_lock)=>{ if (!a_error){ a_res(a_lock); } else { a_rej(a_error); } }); }); console.log(`PID:${process.pid}: ${new Date().toISOString()}: Start of critical section`); await new Promise((a_res, a_rej)=>{ setTimeout(()=>{ a_res(0); }, 1000); }); console.log(`PID:${process.pid}: ${new Date().toISOString()}: End of critical section`); await new Promise((a_res, a_rej)=>{ libLock.unlockNamedMutex(lock, (a_error)=>{ if (!a_error){ a_res(); } else { a_rej(a_error); } }); }); console.log(`PID:${process.pid}: ${new Date().toISOString()}: Process is exit`); } main();

Output:

PID:9412: 2023-10-21T17:34:38.246Z: "Wait locking ..." PID:9413: 2023-10-21T17:34:38.246Z: "Wait locking ..." PID:9413: 2023-10-21T17:34:38.251Z: Start of critical section PID:9413: 2023-10-21T17:34:39.253Z: End of critical section PID:9413: 2023-10-21T17:34:39.254Z: Process is exit PID:9412: 2023-10-21T17:34:39.254Z: Start of critical section PID:9412: 2023-10-21T17:34:40.256Z: End of critical section PID:9412: 2023-10-21T17:34:40.257Z: Process is exit