Golang

[Golang] 채널, 컨텍스트

GenieLove! 2022. 4. 18. 00:08
728x90
반응형

1.채널 - 고루틴끼리 메시지를 전달할 수 있는 메시지 큐

var channel1 chan string = make(chan string)//크기가 0인 채널 생성 -> 처음에 데이터를 빼야 담을 수 있다.

//beffer - 내부에 데이터를 보관할 수 있는 메모리 영역
var channel2 chan string = make(chan string, 3)//beffer 크기가 2인 채널 생성 -> 2개까지 데이터 빼기 전에 저장할 수 있다.

var message string = <- channel1//channel1에 들어가 있는 데이터 추출

channel2 <- "message"//channel2에 데이터 삽입

2. channel이용한 select문

select {
case n := <- channel1://channel1에서 데이터 추출할 수 있을 때 실행
	...
case n2 := <- channel2://channel2에서 데이터 추출할 수 있을 때 실행
	...
}

func timeFunc(channel chan int) {
	time.Sleep(10 * time.Second)
    channel <- 1
}
    
//1초마다 반복하는 코드
func main() {
	tick := time.Tick(time.Second)//1초마다 시그널
   	channel := make(chan int)
    <- channel
    go timeFunc(channel)
    L:
        for {
            select {
            case <- tick:
                fmt.Println("tick~")
            case <- channel:
                fmt.Println("end~")
                break L//레이블이 있는 위치 break
            }
        }
     
}

3.컨텍스트 - 작업 시간, 작업 취소 등의 조건을 지시할 수 있는 명세서 역할

ctx1, cancel1 := context.WithCancel(context.Background())//취소 가능한 컨텍스트 생성
defer cancel1()

ctx2, cancel2 := context.WithTimeout(context.Background(), 1*time.Second)//작업 시간 설정한 컨텍스트 생성(설정한 시간 동안)
defer cancel2()

ctx3, cancel3 := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second)//작업 종료 시간 설정(설정한 시간까지)
defer cancel3()

ctx := context.WithValue(context.Background(), "name", "genie")//특정 값 설정한 컨텍스트 생성
if v := ctx.Value("name"); v != nil {
	fmt.Println(v)
}
728x90
반응형

'Golang' 카테고리의 다른 글

Error Is, As  (0) 2022.10.15
[Golang] Closure  (0) 2022.04.18
[Golang] 고루틴과 동시성  (0) 2022.04.17
[Golang] Gin-Swagger  (0) 2022.03.30
[Golang] 에러 핸들링  (0) 2022.03.24