1

I'm looking for a mutex in object editing for javascript.

The exact problem is this : I'm reading asynchronously from several files. and collecting info to a single object. This can get down to this toy-example

var o = {};
files_list.forEach(function(fpath){fs.readFile(fpath,
    function(err,content){
        var k = Math.floor((Math.random()*10)+1);
        if(o[k])
            {o[k].push(content);}
        else
            {o[k]=[content];} 
    }
);

As I understand it, since readFile is asynchronous, several files might be opened at once.

So what I want is to make access to object o mutually exclusive in each reading callback, so that two simultaneous readings won't mess it up.

What is the way to guarantee that with javascript ? (except for synchronous reading)

(explicit answer given here below)

user3617487
  • 155
  • 11
  • Possible duplicate of [Mutual Exclusion for N Asynchronous Threads](https://stackoverflow.com/questions/3693550/mutual-exclusion-for-n-asynchronous-threads) – Liam Mar 13 '18 at 16:05
  • Javascript does not do mutal exclusion well. you may well be suffering from the [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) problem though – Liam Mar 13 '18 at 16:08
  • Is the issue that you need the read to run in order or is it just your worried about the callback running at the same time? what does *several files might be opened at once* mean? Yes several files might be opened at the same time, why is this an issue? – Liam Mar 13 '18 at 16:35
  • My concern is that two call back might be executed "at the same time", meaning that one might start its execution, and the other might interrupt and execute. So if I get what you're saying that wont happend ? Meaning each call back will be executed at once, with no interruption from another ? – user3617487 Mar 13 '18 at 17:16
  • there are a lot of contradicting answers... any pointer on the event loop that might go into details about interruptions please ? – user3617487 Mar 13 '18 at 18:09
  • 1
    The two callbacks won't happen at the same time. Nothing happens at the same time in JS. They will happen in a non-sequential order but not at the same time. JS is single threaded. – Liam Mar 14 '18 at 09:35
  • 1
    Ok, to sum up what I understood : "event loop + single thread" means "no interruption in the sequence" and so in what concerns my question it means "if a piece of code don't call any asynchronous function, the execution will be atomic ". Is that correct ? – user3617487 Mar 14 '18 at 15:29
  • Yes that is correct – Liam Mar 14 '18 at 15:45
  • 1
    [Summed up nicely here](https://stackoverflow.com/a/7266985/542251) – Liam Mar 14 '18 at 15:46

0 Answers0