microsoft / napajs

Napa.js: a multi-threaded JavaScript runtime
Other
9.24k stars 342 forks source link

console.log print newline incorrectly #184

Open Meigyoku-Thmn opened 6 years ago

Meigyoku-Thmn commented 6 years ago

On my computer, this example: https://github.com/Microsoft/napajs/tree/master/examples/tutorial/synchronized-loading print out result like this (notice the first three [lookupPhoneNumber] lines):

[lookupPhoneNumber] Start to lookup phone number of lisa.[lookupPhoneNumber] Start to lookup phone number of david.

[lookupPhoneNumber] Start to lookup phone number of wade.
[load_data] loading...
[lookupPhoneNumber] lisa : 567-888-9999.
[lookupPhoneNumber] david : 123-444-5555.
[lookupPhoneNumber] wade : <not found>.
[run] All operations are completed.

So somehow the second console.log inserts its string between the first string and the first newline?

"[lookupPhoneNumber] Start to lookup phone number of lisa" "\n"
                                                          ^
                                                          "[lookupPhoneNumber] Start to lookup phone number of david.\n"

I ran this on Nodejs v8.9.1, Windows 10 64 bit.

fs-eire commented 6 years ago

Hi @Meigyoku-Thmn thanks for the feedback. If you try to run the example multiple times, you may found the output may be different.

This is because console.log() is not thread-safe. There is no such thread-safety concern in browser or Node.js because it is single thread. In Napa.js, however, we may have the racing condition. For some API we implemented them in thread-safety (such as store API) way but some others (such as console.log) are not. A function that outputs some message to the standard output isn't necessary to be thread-safe.

If you want to make it thread-safe, you can create a lock, transport it to each worker (use store or pass it in argument list of zone.execute), and use lock.guardSync to synchronize the function. This works but is not recommended, because it does have the performance hit on the execution.