Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/harish2704/node-standalone-mutex
A standalone Mutex implementation for Nodejs which depends on Nodes inter-process communication
https://github.com/harish2704/node-standalone-mutex
cluster lock mutex nodejs promise
Last synced: about 1 month ago
JSON representation
A standalone Mutex implementation for Nodejs which depends on Nodes inter-process communication
- Host: GitHub
- URL: https://github.com/harish2704/node-standalone-mutex
- Owner: harish2704
- License: mit
- Created: 2017-07-05T03:37:47.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-07-06T05:30:42.000Z (over 7 years ago)
- Last Synced: 2024-11-13T08:39:18.262Z (about 2 months ago)
- Topics: cluster, lock, mutex, nodejs, promise
- Language: JavaScript
- Size: 5.86 KB
- Stars: 2
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[![Build Status](https://travis-ci.org/harish2704/node-standalone-mutex.svg?branch=master)](https://travis-ci.org/harish2704/node-standalone-mutex)
# standalone-mutex
A standalone Mutex implementation for Nodejs which depends on Nodes inter-process communication## Installation
```
npm i standalone-mutex
```## Usage
### Example
Below code can be found in `example` directory
```javascript
const cluster = require('cluster');
const numCPUs = parseInt( process.env.THREAD_COUNT || require('os').cpus().length );
const Mutex = require('standalone-mutex');
const log = console.log.bind( console, 'Info: ');const MID = 'asdf65498'; // A unique id for indentifying our mutex.
function delay( ms ){
return new Promise(function(resolve){
setTimeout( resolve, ms );
});
}function doAsync( pid ){
let mutex;
return Mutex.acquire( MID )
.then(function( m ){
mutex = m;
log('doAsync:start ' + pid );
return delay(2000);
})
.then(function(){
log('doAsync:done ' + pid );
return mutex.release();
});
}function master(){
log(`Master ${process.pid} is running`);// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
Mutex.init();doAsync( process.pid ).catch( log );
cluster.on('exit', (worker, code, signal) => {
log(`worker ${worker.process.pid} died ${signal}`);
});
}function slave(){
doAsync( process.pid )
.catch(function(err){
log( 'Error', err );
})
.then(function(){
log( `Completed ${process.pid}`);
});log(`Worker ${process.pid} started`);
}if (cluster.isMaster) {
master();
} else {
slave();
}```