Corey Ogburn
Corey Ogburn

Reputation: 24759

What exactly are goroutines?

The tutorials and documentation I've read all say that goroutines are "not quite threads" or "lightweight threads" but can usually be treated like they are their own separate thread.

So... What are they really?

Upvotes: 5

Views: 5340

Answers (3)

Deleplace
Deleplace

Reputation: 7782

This Morsing's blog post about the Go scheduler is nice because it has pictures with triangles, squares and circles.

From the scheduler's point of view :

The goroutine includes the stack, the instruction pointer and other information important for scheduling.

Upvotes: 0

twotwotwo
twotwotwo

Reputation: 30097

A few things distinguish goroutines from typical OS threads:

  • There's user-mode scheduling. When a goroutine is blocked (waiting on the network, say), the Go runtime looks for another one that can run. This happens without having to enter and exit kernel mode and without the OS kernel's scheduler running.
  • There isn't only user-mode scheduling: to use multiple cores, Go will start multiple OS threads and run goroutines on all of them, potentially moving a goroutine between OS threads to keep everything busy. If you hear that goroutines are "multiplexed" onto OS threads, that's what it means.
  • They're meant to have low cost to start. Stacks start out small, only a few kilobytes and growing as needed, whether the OS is using virtual-memory overcommit or not.
  • They're tied in with the language; besides the go statement itself, there are channel types and operations and select statements for coordinating the goroutines.
  • They lack some OS threading features: currently, Go's scheduler doesn't guarantee fairness, and there's only very limited pre-emption (an empty for{} loop will never be switched away from).

They're closely related to lots of other terms:

  • fibers, a term used in connection with user-mode-scheduled threads
  • green threads, another term used to refer to user-mode-scheduled threads
  • coroutines, referring to routines that can yield control to each other at arbitrary points in their code
  • event-driven architectures, which might switch to other tasks while waiting on asynchronous events like network I/O, but may not present a thread-like interface (they might use callback functions instead, for example)
  • M:N hybrid threading, which involves both kernel- and user-mode threads, and can involve migration of user-mode threads across OS threads.

Upvotes: 23

mattn
mattn

Reputation: 7733

When having two CPUs, goroutine(s) runs as real threads. When having single CPU, the goroutine(s) runs as co-routine of single thread that running with switching their contexts. goroutine doesn't stick the fixed thread. So it doesn't identifier like thread-id. If you want to stick goroutine as OS thread, you need to use runtime.LockOSThread().

Upvotes: 1

Related Questions