Files
  • main.go
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// main.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"sync"
	"sync/atomic"
	"time"
)

var processes_counter uint32 = 0
var total_received uint64 = 0

const number_of_processes = 5 //This is for demo only, in production this could be millions.

func light_process(messages_ch <-chan string, wg *sync.WaitGroup) {
	defer wg.Done()

	process_id := processes_counter

	atomic.AddUint32(&processes_counter, 1)

	for {
		message, continue_ := <-messages_ch

		if continue_ {
			atomic.AddUint64(&total_received, 1)
			fmt.Printf("%s Recieved by process with id %d.\n", message, process_id)
			time.Sleep(2 * time.Second)
		} else {
			fmt.Printf("Process with id %d is closing...\n", process_id)
			return
		}
	}
}

func main() {

	var total_sent uint64 = 0
	var wg sync.WaitGroup
	messages_ch := make(chan string, number_of_processes*100)

	for i := 1; i <= number_of_processes; i++ {
		wg.Add(1)
		go light_process(messages_ch, &wg)
	}

	reader := bufio.NewReader(os.Stdin)

	for {
		fmt.Println("Enter command: ")
		cmd_input, _ := reader.ReadString('\n')

		switch strings.ToUpper(strings.Trim(cmd_input, " \r\n")) {
		case "CHECK":
			fmt.Printf("Total sent: %d, total received: %d.\n", total_sent, total_received)

		case "EXIT":
			goto EXITAPP

		case "SEND":
			for i := 1; i <= 12; i++ {
				total_sent++
				messages_ch <- "Sent from main."
			}
		}
	}

EXITAPP:

	fmt.Println("Closing processes...")
	close(messages_ch)
	wg.Wait()
	fmt.Println("Closing application...")

}