Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between Goroutine and Thread in Golang.
Goroutines and threads are both mechanisms for concurrent execution, but they work at different levels. Goroutines are lightweight, user-space concurrency primitives managed by the Go runtime, while threads are OS-level constructs managed by the operating system kernel.
Goroutine
A goroutine is a function or method that executes independently and concurrently with other goroutines. Every concurrent activity in Go is typically implemented as a goroutine. Goroutines start with just a few kilobytes of stack space (which grows dynamically) and are multiplexed onto a small number of OS threads by the Go runtime scheduler.
Example
The following program launches two goroutines that run concurrently with the main function ?
package main
import (
"fmt"
"time"
)
func sayHello(name string) {
fmt.Println("Hello,", name)
}
func main() {
go sayHello("World")
go sayHello("Go")
time.Sleep(100 * time.Millisecond)
fmt.Println("Done")
}
The output of the above code is ?
Hello, World Hello, Go Done
Note − The order of "Hello, World" and "Hello, Go" may vary because goroutines run concurrently.
Thread
A thread is a lightweight process managed by the operating system. Each thread has its own stack (typically 1–8 MB), a unique thread ID, and thread-local storage. The OS kernel handles scheduling, context switching, and resource allocation for threads.
Key Differences
| Feature | Goroutine | Thread |
|---|---|---|
| Managed By | Go runtime | Operating system kernel |
| Stack Size | ~2 KB (growable dynamically) | ~1–8 MB (fixed) |
| Hardware Dependency | Independent of hardware | Dependent on hardware/OS |
| Communication | Channels (built-in, safe) | Shared memory, mutexes (manual synchronization) |
| Latency | Low latency communication via channels | Higher latency (locks, shared memory) |
| Identity | No thread-local storage, no unique ID | Has thread-local storage and unique ID |
| Scheduling | Cooperatively scheduled by Go runtime | Preemptively scheduled by OS |
| Startup Time | Very fast (microseconds) | Slower (milliseconds) |
| Scalability | Millions of goroutines possible | Thousands of threads (limited by OS) |
Conclusion
Goroutines are extremely lightweight, start faster, use less memory, and communicate safely through channels, making Go ideal for highly concurrent applications. OS threads are heavier but provide preemptive scheduling and direct hardware access. The Go runtime multiplexes many goroutines onto fewer OS threads for optimal performance.
