user3205479
user3205479

Reputation: 1523

Implementation of Go-routines vs Task Parallel Library

I have just started learning Go. The strength of Go lies in goroutines for handling multiple concurrent connections. It was mentioned

Goroutines can be considered as light-weight threads (but not actually threads) which can grow/shrink stack size and these are multiplexed into multiple os threads. Say if you have 1000 goroutines then these are scheduled to native OS threads based on blocking and waiting modes of goroutines.

Basically, I am from C# and Nodejs background. I am pretty confused how it is different from TaskParallelLibrary implemented in C#.

TaskParallelLibrary hides the complexity of creating threads and managing them. You just start a task and CLR takes care of mapping them to native threads. Here you can create thousands of tiny tasks which are mapped and scheduled to OS threads. However TPL solves async problems specifically.

My question is how TPL is different from goroutines? Do goroutines use coroutines (pausable functions or?). TPL also multiplexes the async/syscalls operations to the thread pool, even Go also multiplexes syscalls to the thread pool.

Correct me if any of my assumptions are wrong. Could anyone help me where exactly the implementation differs? Why do goroutines claim to be faster than TPL?

Upvotes: 5

Views: 2728

Answers (1)

kostix
kostix

Reputation: 55453

The chief difference is that Go runtime tightly couples scheduling of the goroutines with I/O which basically works like this: if a goroutine is about to block on some I/O operation or on a channel operation, the scheduler suspends that goroutine and re-activates it once it knows the original I/O or channel operation can now proceed. This allows writing Go code in purely sequential manner—without all the callback hell and "futures"/"promises" kludges, which merely wraps callbacks into objects, and also without async/await machinery which, again, merely couples compiler tricks with plain OS threads.

This stuff is very good explained in this classic piece by one of the developers of the Dart programming language.

Also see this and this.

Upvotes: 5

Related Questions