简体   繁体   中英

race condition issue in node?

People says that single-threaded languages like Javascript can not got that issue. However, nodejs provides cluster to fork multiple workers. Is this gonna cause race condition problem?

And also, I have an example that causes my confusion sometimes:

ALLSESSIONS = {};
//session id saved in cookie
ALLSESSIONS[sessionid] = 'somevalue';

var SESSION = ALLSESSIONS[sessionid];
... do stuff for sometimes
console.log(SESSION);

I'm afraid that when another request reaches node while the current request is still running, it may overwrite the SESSION variable with its own session id, then the result of current request is undetermined .

Is this gonna happen in node?

When another request reaches node while the current request is still running, it will not overwrite the session variable with its own.

Cluster allows you to have multiple workers, and these workers will all be separate from each other. This means that if your ALLSESSIONS variable is scoped to a single worker, then it will actually only contain session information for the given worker. You would need your ALLSESSIONS variable to be scoped at the application (pre-fork) level in order to share it across workers.

However, keeping session information in memory is probably not a good idea to begin with! If your worker or application threads crash, then you've lost your session data. It may be better to use a persistent store of some sort.

In general, race conditions are likely to occur if you have a globally scoped variable being written to and read from multiple request threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM