SoFunction
Updated on 2025-03-02

Implementation of golang concurrent programming

go

The execution of the main function itself is a coroutine. When using the go keyword, a new coroutine will be created.

channel

channel pipeline for passing signals between multiple coroutines

No cache pipeline

When writing to an unbuffered channel, it will block and wait until a coroutine reads the buffered channel.

Blocking scenario:

  1. There is no data in the channel, but the read channel is performed.
  2. There is no data in the channel, and data is written to the channel, but no coroutine reads.

In summary, read and write without cache channels must exist at the same time, and read and write in two different coroutines.

func main(){
  ch := make(chan int)
  
  go func(ch chan int){
    ch <-222
  }(ch)
  
  println(<-ch)
}

Buffered pipe

When there is a cache, you can write data to the channel and return it directly. When there is data in the cache, you can read the data from the channel and return it directly. At this time, the cache channel will not block.

Blocking scenario:

  1. The cache of the channel has no data, but the read channel is performed.
  2. The cache of the channel is already full, and data is written to the channel, but there is no coroutine reading.

In summary, the read and write with buffered channels must be in two different coroutines.

func main() {
  ch := make(chan int, 1) //The buffered pipe with length 1 also has buffered pipes  ch &lt;- 333
  go func(ch chan int) {
    println(&lt;-ch)
  }(ch)
  ch &lt;- 333
}

and

Concurrent lock, only one concurrent lock can be loaded at a time

Read and write lock, multiple read locks and one write lock can be loaded at a time. When the write lock exists, the read lock and the write lock cannot be loaded again.


Block and wait for all tasks to complete before continuing execution

WaitGroup is passed in no method, and a pointer is required

func main() {
  var wg 
  ch := make(chan int, 1000)
  for i := 0; i < 1000; i++ {
    (1)
    go doSomething(i, &wg, ch)
  }
  ()
  ("all done")
  for i := 0; i < 1000; i++ {
    dd := <-ch
    ("from ch:"+(dd))
  }
}

func doSomething(index int, wg *, ch chan int) {
  defer ()
  ("start done:" + (index))
  //(20 * )
  ch <- index
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.