Skip to content

Commit c29c5ed

Browse files
author
hamed
committed
Wait groups example added
1 parent 82581bf commit c29c5ed

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module waitGroup
2+
3+
go 1.18
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"strconv"
8+
"sync"
9+
)
10+
11+
var TodoList = []string{}
12+
13+
func main() {
14+
wg := sync.WaitGroup{}
15+
wg.Add(50) // 50 - 50 = 0
16+
for i := 0; i < 50; i++ {
17+
//wg.Add(1)
18+
go GetTodo(i+1, &wg)
19+
}
20+
21+
wg.Wait()
22+
fmt.Printf("%v", TodoList)
23+
24+
}
25+
26+
func GetTodo(id int, wg *sync.WaitGroup) {
27+
//"https://jsonplaceholder.typicode.com/todos/1"
28+
GetUrl("https://jsonplaceholder.typicode.com/todos/"+strconv.Itoa(id), wg)
29+
}
30+
31+
func GetUrl(url string, wg *sync.WaitGroup) {
32+
defer wg.Done()
33+
response, err := http.Get(url)
34+
35+
if err != nil {
36+
panic(err)
37+
}
38+
39+
responseBody, err := io.ReadAll(response.Body)
40+
defer response.Body.Close()
41+
42+
if err != nil {
43+
panic(err)
44+
}
45+
46+
TodoList = append(TodoList, string(responseBody))
47+
48+
}
49+
50+
// main =>
51+
// fork task1 task2 task3 task4 task5
52+
53+
//join
54+
55+
// 5
56+
// -1 => 4
57+
// -1 => 3
58+
// ...
59+
// -1 => 0

0 commit comments

Comments
 (0)