Quick actions

cmd+k|ctrl+k

Navigation

Languages

Concurrency (goroutine + waitgrup

Snippet info

Language

Go

Visibility

public

Author

riki.whyudi

Created

2023-09-02T10:40:55.077276Z

Updated

2023-09-02T12:03:13.019455Z

package main

import (
	"fmt"
	"sync"
	"time"
)

func Runner() map[int]string {
	results := make(map[int]string)
	var wg sync.WaitGroup

	// Stage 1: Membuat goroutine untuk setiap pekerja dengan WaitGroup
	for i := 1; i <= worker; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			res, err := mockGetData(id)
			if err != nil {
				return
			}
			results[res.ID] = res.Title
		}(i)
	}

	// Menunggu semua goroutine selesai
	wg.Wait()
	return results
}

type (
	Result struct {
		ID    int    `json:"id"`
		Title string `json:"title"`
	}
)

const worker = 3

var (
	expectedWorker                = 0
	expected       map[int]string = map[int]string{
		1: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
		2: "qui est esse",
		3: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
	}
)

func main() {
	results := Runner()

	// Menampilkan hasil dari Runner
	for id, title := range results {
		fmt.Printf("ID: %d, Title: %s\n", id, title)
	}
}

func mockGetData(id int) (*Result, error) {
	expectedWorker++
	time.Sleep(2 * time.Second)

	result := Result{
		ID:    id,
		Title: expected[id],
	}
	expected[id] = result.Title
	return &result, nil
}
INFO