Move: multi threaded examples to sub folder
This commit is contained in:
parent
3db7a906de
commit
ef722eec2f
2 changed files with 0 additions and 0 deletions
25
multi-threading/basic-multi-threaded.go
Normal file
25
multi-threading/basic-multi-threaded.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Function that prints numbers from 1 to 5 with a delay
|
||||
func printNumbers(id int) {
|
||||
for i := 1; i <= 5; i++ {
|
||||
fmt.Printf("Goroutine %d: %d\n", id, i)
|
||||
time.Sleep(100 * time.Millisecond) // Delay for visibility
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Launch 3 goroutines
|
||||
for i := 1; i <= 3; i++ {
|
||||
go printNumbers(i)
|
||||
}
|
||||
|
||||
// Wait for goroutines to finish
|
||||
time.Sleep(1 * time.Second) // Ensure main does not exit immediately
|
||||
fmt.Println("All goroutines finished")
|
||||
}
|
50
multi-threading/sync-multi-threaded.go
Normal file
50
multi-threading/sync-multi-threaded.go
Normal file
|
@ -0,0 +1,50 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Task struct representing a task to be processed
|
||||
type Task struct {
|
||||
id int
|
||||
}
|
||||
|
||||
// Worker function that processes tasks from the task channel
|
||||
func worker(id int, tasks <-chan Task, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for task := range tasks {
|
||||
fmt.Printf("Worker %d processing task %d\n", id, task.id)
|
||||
time.Sleep(time.Millisecond * 500) // Simulate work
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
const numWorkers = 3
|
||||
const numTasks = 10
|
||||
|
||||
// Create a channel to send tasks to workers
|
||||
tasks := make(chan Task, numTasks)
|
||||
|
||||
// Create a WaitGroup to wait for all workers to finish
|
||||
var wg sync.WaitGroup
|
||||
|
||||
// Start worker goroutines
|
||||
for i := 1; i <= numWorkers; i++ {
|
||||
wg.Add(1)
|
||||
go worker(i, tasks, &wg)
|
||||
}
|
||||
|
||||
// Send tasks to the task channel
|
||||
for i := 1; i <= numTasks; i++ {
|
||||
tasks <- Task{id: i}
|
||||
}
|
||||
|
||||
// Close the task channel to signal no more tasks
|
||||
close(tasks)
|
||||
|
||||
// Wait for all workers to finish
|
||||
wg.Wait()
|
||||
fmt.Println("All tasks processed")
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue