10/02 Study Daily record

손진성·2022년 2월 10일
0

Select Statement Definition

  • Select statement allows our code to wait on multiple channels at the same time
  • Select blocks until one channel is ready
  • If multiple channels are ready, Select picks one at ramdom

Select Syntax

Select{
	case value1 := <- channel1:
    //code
    case channel 2 <- value2:
    //code

Test Exercise

  • Assume we are writing spaceship software
  • We will write a simple program to retrive security clearance for the different crew members
  • The program will try to retrive data from two database servers concurrently for maximum efficiency
  • Once any of the servers return the data, we print the security clearance and return

Code

package main

import (
	"fmt"
	"math/rand"
	"time"
)

var scMapping = map[string]int{
	"James": 5,
	"Kevin": 10,
	"Rahul": 9,
}

func findSC(name, server string, c chan int) {
	//Simulate searching
	time.Sleep(time.Duration(rand.Intn(50)) * time.Minute)

	//return security clearance from map
	c <- scMapping[name]
}

func main() {

	rand.Seed(time.Now().UnixNano())

	c1 := make(chan int)
	c2 := make(chan int)

	name := "James"

	go findSC(name, "Server 1", c1)
	go findSC(name, "Server 2", c2)

	/*
		Do some work...
	*/

	select {
	case sc := <-c1:
		fmt.Println(name, "has a security clearance of ", sc, "found in server1 ")
	case sc := <-c2:
		fmt.Println(name, "has a security clearance of ", sc, "found in server2 ")
	default:
		fmt.Println("Too slow!!")
	}

}
  • rand.Intn(50) : Intn returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). It panics if n <= 0.
  • rand.Seed(time.Now().UnixNano()) :
    • The initial value from which the random value is calculated is the same.This initial value is called the random seed. In order to produce a different random value each time the program is executed, the random seed must be set to a different value each time.
    • UnixNano: Returns the Unix time in nanoseconds
    • Unix time is a way of representing time. It is also called POSIX time or Epoch time. The time since January 1, 1970 00:00:00 Coordinated Universal Time (UTC) is converted into seconds and expressed as an integer.
    • This is a method of displaying the time on a computer using a Unix-like operating system. Shows how many seconds have passed since January 1, 1970 0:0:0 UTC.
  • When there is a default case inside the Select the select will not lock.
profile
Gopyther

0개의 댓글