In a recent “technical discussion”, I was asked “how do you accomplish multithreading using a single thread?” After confirming that the interviewer did not consider this a trick question, I had to admit that I didn’t have a good idea how to achieve multithreading on a single thread, and further, that I considered the question a bit of a contradiction. The answer the interviewer provided, “by using a multicast delegate,” left me wondering if maybe he didn’t really understand delegates and the underlying threading. I would be interested to know if the question has any merit and, more importantly, if the associated answer makes any sense. Thank you.
Coroutines are something done to simulate cooperative multithreading (not supported by .NET, unless we consider the async
/await
pattern to be a coroutine pattern).
Asynchronous programming simulates multithreading (at least partially... More than one read/write for example is executed at the same time)... Both are possible solutions that hide the "threading" part.
To elaborate on the asynchronous programming... One could build an entire web server, able to respond to hundred of requests at the same time, based on a single thread + asynchronous elaboration. Each read from the disk would be done asynchronously. Every response to the connecting clients would be done asynchronously and so on.
To give a name, from what I comprehend, node.js is a single threaded web server entirely based on asynchronous programming (technically called non blocking I/O)... See for example https://stackoverflow.com/a/14797359/613130
To what I've written, I'll add that there are some languages that implement what is called Green threads. Green threads are cooperative threads that don't use the OS scheduler. Their code so is executed in a single thread (at least from their point of view). It seems that Go, haskell, old Ruby, various versions of Smalltalk all use/used green threads).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With