|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "math/rand" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +var MAX_CHICKEN_PRICE float32 = 5 |
| 10 | +var MAX_TOFU_PRICE float32 = 3 |
| 11 | + |
| 12 | +func main(){ |
| 13 | + var chickenChannel = make(chan string) |
| 14 | + var tofuChannel = make(chan string) |
| 15 | + var websites = []string{"swiggy", "zomato", "eatclub"} |
| 16 | + for i:= range websites{ |
| 17 | + go checkChickenPrices(websites[i], chickenChannel) |
| 18 | + go checkTofuPrices(websites[i], tofuChannel) |
| 19 | + } |
| 20 | + sendMessage(chickenChannel, tofuChannel) |
| 21 | +} |
| 22 | + |
| 23 | +func checkChickenPrices(website string, chickenChannel chan string){ |
| 24 | + for { |
| 25 | + time.Sleep(time.Second+1) |
| 26 | + var chickenPrice = rand.Float32()*20 |
| 27 | + if chickenPrice<=MAX_CHICKEN_PRICE{ |
| 28 | + chickenChannel <- website |
| 29 | + break |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func checkTofuPrices(website string, tofuChannel chan string){ |
| 35 | + for { |
| 36 | + time.Sleep(time.Second+1) |
| 37 | + var tofuPrice = rand.Float32()*20 |
| 38 | + if tofuPrice<=MAX_TOFU_PRICE{ |
| 39 | + tofuChannel <- website |
| 40 | + break |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +func sendMessage(chickenChannel chan string, tofuChannel chan string){ |
| 46 | + select{ |
| 47 | + case website := <-chickenChannel: |
| 48 | + fmt.Printf("\nText Sent: Found deal on chicken at %v.", website) |
| 49 | + case website := <-tofuChannel: |
| 50 | + fmt.Printf("Email Sent: Found deal on tofu at %v.", website) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | +// func main() { |
| 57 | +// //var c = make(chan int) |
| 58 | +// var c = make(chan int, 5) //by adding this process function will run immediately but main function will take time |
| 59 | +// //go process(c) |
| 60 | +// go process2(c) |
| 61 | +// fmt.Println(<-c) |
| 62 | +// for i:= range c{ |
| 63 | +// fmt.Println(i) |
| 64 | +// time.Sleep(time.Second+1) |
| 65 | +// } |
| 66 | +// } |
| 67 | + |
| 68 | +// // func process(c chan int){ |
| 69 | +// // c <- 123 |
| 70 | +// // } |
| 71 | + |
| 72 | +// func process2(c chan int){ |
| 73 | +// defer close(c) |
| 74 | +// for i:=0; i<5; i++{ |
| 75 | +// c <- i |
| 76 | +// } |
| 77 | +// fmt.Println("Exiting Process") |
| 78 | +// } |
| 79 | + |
| 80 | +/* |
| 81 | +var c = make(chan int) //this channel can only hold a single int value |
| 82 | +c <- 1 // adding value to this channel |
| 83 | +var i = <-c // retrieve the value from the channel now c will be empty and i = 1 |
| 84 | +fmt.Println(i) |
| 85 | +
|
| 86 | +if we run the above code direclty it will give deadlock error |
| 87 | +*/ |
0 commit comments