10

I have a socket.io server which listens to sockets:

io.sockets.on('connection', function(socket){
    socket.on('myEvent', function(data){
        socket.emit('eventReceived', { status: 1 });
    });
});

Is this code working in multithread? if two clients will emit the myEvent event, it will work at the same time for both clients? or it will be handled one after the other?

Many thanks!

udidu
  • 8,269
  • 6
  • 48
  • 68
  • 1
    No, it's not multithreaded. Node.js uses a single threaded event loop. See [this answer](http://stackoverflow.com/questions/9362823/why-is-a-function-and-a-callback-non-blocking-in-node-js/9363071#9363071) of mine for a further explanation. – Linus Thiel Apr 30 '12 at 13:12
  • If the Node.js is not multithreaded, it means that the Socket.IO is also not multithreaded? – udidu Apr 30 '12 at 14:35
  • 2
    Exactly. You can scale by running a distributed backend for the messaging, there is a [redis store](https://github.com/LearnBoost/socket.io/blob/master/lib/stores/redis.js) built in. – Linus Thiel Apr 30 '12 at 18:42

1 Answers1

1

Nothing in Node.js is multithreaded including any packages available through npm. There is an experimental cluster module available in the core

http://nodejs.org/docs/v0.10.2/api/cluster.html

fncomp
  • 6,040
  • 3
  • 33
  • 42
deltanovember
  • 42,611
  • 64
  • 162
  • 244
  • 2
    Just because Node.js has a single event loop does not mean the asynchronous processes under the hood, behind the scenes, are not multi-threaded. Because many are. Here's one article that addresses one issue in that regard: https://www.future-processing.pl/blog/on-problems-with-threads-in-node-js/ – user1588877 May 04 '17 at 17:49
  • @deltanovember Node IS single-threaded. Referring to that article is misleading. Utilizing the thread pool does not mean you're multi-threaded, it just means you're scheduling tasks. Being multi-threaded implies that you can have multiple things running at the same time (concurrent). Using the thread pool means that the OS will execute them in the most efficient way it can which mean it MIGHT be concurrent. In all cases, Node has no control over it. Asynchronous just means you're not waiting for it to finish before continuing and thus not blocking (like promises) – Sinaesthetic Aug 14 '18 at 18:01
  • Event languages that support multi-threading make this distinction. Like in C#, async/await and Thread are two completely different things. – Sinaesthetic Aug 14 '18 at 18:02
  • the libuv of node.js is multithreaded too, so Node.js is single-threaded but it doesn't mean every library of it is! so it may can even some npm packages not be too! – Amir Hossein Dec 19 '20 at 23:45