Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Go Concurrency

Go Concurrency

Concurrency refers to the ability of a program to execute multiple tasks at the same time.

Go supports concurrency, providing a simple and efficient way to achieve it through goroutines and channels.

Goroutines:

Channel:

Scheduler:

Go's scheduler is based on the GMP model; it assigns Goroutines to system threads for execution and efficiently manages concurrency through the cooperation of M and P.


Goroutine

A goroutine is a lightweight thread, and goroutine scheduling is managed by the Golang runtime.

goroutine syntax:

go 函数名( 参数列表 )

For example:

go f(x, y, z)

Start a new goroutine:

f(x, y, z)

Go allows the use of a go statement to start a new runtime thread, namely a goroutine, to execute a function in a different, newly created goroutine. All goroutines in the same program share the same address space.

Example

package

main

import

(

       

"fmt"

       

"time"

)

func

sayHello

()

{

       

for

i

:=

0

;

i

<

5

;

i

++

{

                fmt

.

Println

(

"Hello"

)

                time

.

Sleep

(

100

time

.

Millisecond

)

       

}

}

func

main

()

{

       

go

sayHello

()

// Start a Goroutine

       

for

i

:=

0

;

i

<

5

;

i

++

{

                fmt

.

Println

(

"Main"

)

                time

.

Sleep

(

100

time

.

Millisecond

)

       

}

}

Running the above code, you will see Main and Hello printed. The output has no fixed order because they are two goroutines executing:

Main

Hello

Main

Hello

...


Channel

A channel is used for data transfer between Goroutines.

Channels can be used to synchronize and communicate between two goroutines by passing a value of a specified type.

Use make The function creates a channel, using the <- operator to send and receive data. If no direction is specified, it is a bidirectional channel.

ch <- v    // 把 v 发送到通道 ch

v := <-ch  // 从 ch 接收数据

           // 并把值赋给 v

Declaring a channel is simple; we just use the chan keyword, and a channel must be created before use:

ch := make(chan int)

Note: By default, channels are unbuffered. When the sender sends data, there must be a corresponding receiver receiving the data at the same time.

The following example uses two goroutines to compute the sum of numbers; after the goroutines finish computing, it calculates the sum of the two results:

Example

package

main

import

"fmt"

func

sum

(

s

[]

int

,

c

chan

int

)

{

    sum

:=

0

   

for

_

,

v

:=

range

s

{

        sum

+=

v

   

}

    c <

sum

// Send sum to channel c

}

func

main

()

{

    s

:=

[]

int

{

7

,

2

,

8

,

9

,

4

,

0

}

    c

:=

make

(

chan

int

)

   

go

sum

(

s

[:

len

(

s

)

/

2

],

c

)

   

go

sum

(

s

[

len

(

s

)

/

2

:],

c

)

    x

,

y

:=

<

c

,

<

c

// Receive from channel c

    fmt

.

Println

(

x

,

y

,

x

y

)

}

The output is:

-5 17 12

Channel Buffers

A channel can have a buffer, with the buffer size specified by the second parameter of make:

ch := make(chan int, 100)

A buffered channel allows the sender's data transmission and the receiver's data retrieval to be asynchronous; that is, data sent by the sender can be placed in the buffer and wait for the receiver to retrieve it, rather than requiring the receiver to retrieve it immediately.

However, since the buffer size is limited, there must still be a receiver to retrieve the data; otherwise, once the buffer is full, the sender can no longer send data.

Note: If a channel is unbuffered, the sender blocks until the receiver has received the value from the channel. If the channel is buffered, the sender blocks until the sent value is copied into the buffer; if the buffer is full, it means waiting until some receiver retrieves a value. The receiver blocks until a value is available to receive.

Example

package

main

import

"fmt"

func

main

()

{

   

// Here we define a buffered channel that can store integers

   

// Buffer size is 2

    ch

:=

make

(

chan

int

,

2

)

   

// Because ch is a buffered channel, we can send two values at the same time

   

// without needing to synchronously read the data immediately

    ch <

1

    ch <

2

   

// Retrieve these two values

    fmt

.

Println

(

<-

ch

)

    fmt

.

Println

(

<-

ch

)

}

The execution output is:

1

2

Ranging over Channels and Closing Channels

Go uses the range keyword to iterate over the data read, similar to arrays or slices. The format is as follows:

v, ok := <-ch

If the channel cannot receive data, ok becomes false, and the channel can then be closed using the close() function.

Example

package

main

import

(

   

"fmt"

)

func

fibonacci

(

n

int

,

c

chan

int

)

{

    x

,

y

:=

0

,

1

   

for

i

:=

0

;

i

< n

;

i

++

{

        c <

x

        x

,

y

=

y

,

x

y

   

}

   

close

(

c

)

}

func

main

()

{

    c

:=

make

(

chan

int

,

10

)

   

go

fibonacci

(

cap

(

c

),

c

)

   

// The range function iterates over each value received from the channel; because c sends 10

   

// values and then closes the channel, our range function here ends after receiving 10

   

// values. If channel c above were not closed, the range function would not

   

// end, and would block when trying to receive the 11th value.

   

for

i

:=

range

c

{

        fmt

.

Println

(

i

)

   

}

}

The execution output is:

0

1

1

2

3

5

8

13

21

34

The select Statement

select statement allows a goroutine to wait on multiple communication operations.select blocks until one of the cases can proceed:

Example

package

main

import

"fmt"

func

fibonacci

(

c

,

quit

chan

int

)

{

    x

,

y

:=

0

,

1

   

for

{

       

select

{

       

case

c <

x

:

            x

,

y

=

y

,

x

y

       

case

<

quit

:

            fmt

.

Println

(

"quit"

)

           

return

       

}

   

}

}

func

main

()

{

    c

:=

make

(

chan

int

)

    quit

:=

make

(

chan

int

)

   

go

func

()

{

       

for

i

:=

0

;

i

<

10

;

i

++

{

            fmt

.

Println

(

<

c

)

}

        quit <

0

   

}()

    fibonacci

(

c

,

quit

)

}

In the code above,fibonacci A goroutine sends the Fibonacci sequence on channel c , and exits when it receives a signal on quit channel.

The execution output is:

0

1

1

2

3

5

8

13

21

34

quit


Using WaitGroup

sync.WaitGroup is used to wait for multiple Goroutines to complete.

Synchronizing multiple Goroutines:

Example

package

main

import

(

       

"fmt"

       

"sync"

)

func

worker

(

id

int

,

wg

sync

.

WaitGroup

)

{

       

defer

wg

.

Done

()

// Call Done() when the Goroutine completes

        fmt

.

Printf

(

"Worker %d started\n"

,

id

)

        fmt

.

Printf

(

"Worker %d finished\n"

,

id

)

}

func

main

()

{

       

var

wg sync

.

WaitGroup

       

for

i

:=

1

;

i

<

=

3

;

i

++

{

                wg

.

Add

(

1

)

// Increment the counter

               

go

worker

(

i

,

&wg

)

       

}

        wg

.

Wait

()

// Wait for all Goroutines to complete

        fmt

.

Println

(

"All workers done"

)

}

Running the above code produces the following output:

Worker 1 started

Worker 1 finished

Worker 2 started

Worker 2 finished

Worker 3 started

Worker 3 finished

All workers done


Advanced Features

** Buffered Channel:**

Create a buffered Channel.

ch := make(chan int, 2)

Context:

Used to control the lifecycle of a Goroutine.

context.WithCancel、context.WithTimeout。

Mutex and RWMutex:

sync.Mutex provides a mutual exclusion lock to protect shared resources.

var mu sync.Mutex

mu.Lock()

// critical section

mu.Unlock()


Summary of Concurrent Programming

Go provides powerful concurrency support through Goroutines and Channels, simplifying the complexity of traditional threading models. With the scheduler and synchronization tools, high-performance concurrent programs can be easily implemented.

Common questions

Deadlock:

Data Race: