Open robert-min opened 11 months ago
package main
import (
"fmt"
"sync"
"time"
)
var mutex sync.Mutex
type Account struct {
Balance int
}
func DepositAndWithdraw(account *Account) {
// mutex 획득
mutex.Lock()
defer mutex.Unlock()
if account.Balance < 0 {
panic(fmt.Sprintf("Balance sould not be negative value : %d", account.Balance))
}
account.Balance += 1000
time.Sleep(time.Millisecond)
account.Balance -= 1000
}
func main() {
var wg sync.WaitGroup
account := &Account{0}
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
for {
DepositAndWithdraw(account)
}
wg.Done()
}()
}
wg.Wait()
}
채널은 고루틴끼리 메시지를 전달할 수 있는 메시지 큐
일반적으로 채널을 생성하면 크기가 0인 채널을 만들고, 데이터를 담아둘 곳이 없기 때문에 수신자가 올때까지 대기
버퍼를 가진 채널은 데이터를 보관할 수 있는 메모리 영역을 가짐
var chan string messages = make(chan string, 2)
package main
import (
"fmt"
"sync"
"time"
)
func square(wg *sync.WaitGroup, ch chan int) {
for n := range ch {
fmt.Printf("Square: %d\n", n*n)
time.Sleep(time.Second)
}
wg.Done()
}
func main() {
var wg sync.WaitGroup
ch := make(chan int)
wg.Add(1)
go square(&wg, ch)
for i := 0; i < 10; i++ {
ch <- i * 2
}
// 데이터를 모두 넣고 필요 없어진 채널을 닫음
close(ch)
wg.Wait()
}
package main
import (
"fmt"
"sync"
"time"
)
func square(wg *sync.WaitGroup, ch chan int, quit chan bool) {
for {
select {
case n := <-ch:
fmt.Printf("Square: %d\n", n*n)
time.Sleep(time.Second)
case <-quit:
wg.Done()
return
}
}
}
func main() {
var wg sync.WaitGroup
ch := make(chan int)
quit := make(chan bool)
wg.Add(1)
go square(&wg, ch, quit)
for i := 0; i < 10; i++ {
ch <- i * 2
}
quit <- true
wg.Wait()
}
package main
import (
"context"
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func PrintEverySecond(ctx context.Context) {
tick := time.Tick(time.Second)
for {
select {
case <-ctx.Done():
wg.Done()
return
case <-tick:
fmt.Println("Tick")
}
}
}
func main() {
wg.Add(1)
// context 생성
ctx, cancel := context.WithCancel(context.Background())
go PrintEverySecond(ctx)
time.Sleep(5 * time.Second)
cancel()
wg.Wait()
}
package main
import (
"context"
"fmt"
"sync"
)
var wg sync.WaitGroup
func squre(ctx context.Context) {
if v := ctx.Value("number"); v != nil {
n := v.(int)
fmt.Printf("Squre: %d", n*n)
}
wg.Done()
}
func main() {
wg.Add(1)
// context 생성
ctx := context.WithValue(context.Background(), "number", 9)
go squre(ctx)
wg.Wait()
}
Go routine
sync.WaitGroup