# Golang Concurrency #2 - Goroutines

# Goroutines

Goroutines are Go's lightweight threads. They are not OS threads. They are managed by Go's runtime and are much cheaper to create and destroy.

# Creating a goroutine

```go
go someFunction()  // Runs someFunction concurrently
```

# Basic example

```go
func main() {
    go sayHello()
    sayWorld()
}

func sayHello() {
    fmt.Println("Hello")
}

func sayWorld() {
    fmt.Println("World")
}
```

# Key properties

**Lightweight** → You can spawn thousands or millions of goroutines. Each uses ~2KB of memory initially.

**Multiplexed** → Go runtime maps many goroutines onto fewer OS threads (usually one per CPU core).

**No return values** → Goroutines can't return values directly. Use channels for communication.

**Non-blocking** → `go` keyword doesn't wait for the function to finish.

# Common mistake

```go
func main() {
    go fmt.Println("This might not print")
    // main() exits immediately, killing the goroutine
}
```

# Simple fix

```go
func main() {
    go fmt.Println("This will print")
    time.Sleep(time.Second) // Wait for goroutine
}
```

# With anonymous functions

```go
go func() {
    fmt.Println("Anonymous goroutine")
}()
```

Goroutines are the core of Go concurrency. They make concurrent programming easy. You don't have to manage threads. Just start goroutines and let Go take care of everything else.

# What is a thread?

A thread is a series of instructions that runs on its own. You can think of it as a separate "path of execution" in your program.

# Without threads (sequential)

```go
Step 1: Read file
Step 2: Process data
Step 3: Save result
Step 4: Send email
```

# With threads (concurrent)

```go
Thread 1: Read file → Process data → Save result
Thread 2: Send email
```

Both threads can run at the same time instead of waiting for each other.

# OS threads vs Goroutines

* **OS thread**: Managed by your operating system, heavy (~8MB memory each)
    
* **Goroutine**: Managed by Go runtime, lightweight (~2KB memory each)
    

# What does "running concurrently" mean?

It means multiple pieces of code are in progress at the same time, but not necessarily executing at the exact same moment.

# Example

```go
func main() {
    go downloadFile()    // Starts downloading
    go processData()     // Starts processing
    go sendEmail()       // Starts sending

    // All three are "running concurrently"
}
```

**Concurrent programming** means writing code where multiple tasks can make progress without waiting for each other to complete first.

# Real-world analogy

* **Sequential**: Wash dishes, then dry them, then put them away
    
* **Concurrent**: One person washes while another dries while another puts away
    

The tasks overlap in time rather than happening one after another.
