Pay attention to sharing variables when Node processes in parallel
I encountered a strange bug at work this week. After searching for a long time, I found that it was the reason why a shared object variable was tampered with during parallel computing
Directly upload the code first:
1 | const Promise = require('bluebird'); |
According to the results, we can see that if the passed variables are not deeply copied, the modifications to the same passed object variables between different processes will affect each other. This is because in js, object variables are passed in when passing parameters. It is a reference, so if you directly modify an passed object parameter, it will lead to this situation.
Moreover, in this case, even if the object parameter you pass is const, it is useless, because const only guarantees that the reference address of the variable is unchanged, and there is no constraint on the value stored in the address.
The best way is to directly perform deep copying after passing in parameters.