Skip to Content
Go 소개
book

Go 소개

by Caleb Doxsey
May 2025
Beginner to intermediate
124 pages
1h 15m
Korean
O'Reilly Media, Inc.
Content preview from Go 소개

10장. 동시성

이 작품은 AI를 사용하여 번역되었습니다. 여러분의 피드백과 의견을 환영합니다: translation-feedback@oreilly.com

대규모 프로그램은 여러 개의 작은 하위 프로그램으로 구성되는 경우가 많습니다. 예를 들어 웹 서버는 웹 브라우저의 요청을 처리하고 이에 대한 응답으로 HTML 웹 페이지를 제공합니다. 각 요청은 하나의 작은 프로그램처럼 처리됩니다.

이와 같은 프로그램은 작은 구성 요소를 동시에 실행할 수 있으면 이상적입니다(웹 서버의 경우 여러 요청을 처리하기 위해). 두 개 이상의 작업을 동시에 진행하는 것을 동시성이라고 합니다. Go는 고루틴과 채널을 사용하여 동시성을 풍부하게 지원합니다.

고루틴

고루틴은 다른 함수와 동시에 실행할 수 있는 함수입니다. 고루틴을 만들려면 go 키워드 뒤에 함수 호출을 사용합니다:

package main

import "fmt"

func f(n int) {
    for i := 0; i < 10; i++ {
        fmt.Println(n, ":", i)
    }
}

func main() {
    go f(0)
    var input string
    fmt.Scanln(&input)
}

이 프로그램은 두 개의 고루틴으로 구성됩니다. 첫 번째 고루틴은 암시적이며 주요 함수 자체입니다. 두 번째 고루틴은 go f(0) 을 호출할 때 생성됩니다. 일반적으로 함수를 호출하면 프로그램은 함수의 모든 문을 실행한 다음 호출 후 다음 줄로 돌아갑니다. 고루틴을 사용하면 함수가 완료될 때까지 기다리지 않고 바로 다음 줄로 돌아갑니다. Scanln 함수에 대한 호출이 포함된 이유는 바로 이 때문입니다. 이 함수가 없으면 모든 숫자를 인쇄할 기회를 갖기도 전에 프로그램이 종료됩니다.

고루틴은 가볍기 때문에 수천 개를 쉽게 만들 수 있습니다. 이렇게 하면 10개의 고루틴을 실행하도록 프로그램을 수정할 수 있습니다:

func main() {
    for i := 0; i < 10; i++ {
        go f(i)
    }
    var input string
    fmt.Scanln(&input)
}

이 프로그램을 실행할 때 고루틴이 동시에 실행되지 않고 순서대로 실행되는 것을 보셨을 것입니다. time.Sleep 과 rand.Intn 을 사용하여 함수에 약간의 지연을 추가해 보겠습니다:

package main

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

func f(n int) {
    for i := 0; i < 10; i++ {
        fmt.Println(n, ":", i)
        amt := time.Duration(rand.Intn(250))
        time.Sleep(time.Millisecond * amt)
    }
}

func main() {
    for i := 0; i < 10; i++ {
        go f(i)
    }
    var input string
    fmt.Scanln(&input)
}

이 프로그램을 실행하면 다음과 같은 결과가 생성됩니다:

4 : 0
6 : 0
5 : 0
7 : 0
0 : 0
8 : 0
2 : 0
3 : 0
1 : 0
9 : 0
3 : 1
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

효율적인 Go

효율적인 Go

Bartlomiej Plotka
핸즈온 머신러닝(3판)

핸즈온 머신러닝(3판)

오렐리앙 제롱(Aurélien Géron)
러닝 랭체인

러닝 랭체인

메이오 오신, 누노 캄포스
Go의 동시성

Go의 동시성

Katherine Cox-Buday

Publisher Resources

ISBN: 9798341659827