Talking about the Channel in GO and the cause of deadlock_Golang

Table of contents

  • written in front
  • Primer
  • problem thrown
  • problem explanation
  • keep going
  • write on the back

written in front

This article was born thanks to the MIT 6.284 course. In one of the lessons, I talked about some issues of multi-threaded collaboration, which involved the concept of channel, and a piece of code triggered thinking and gradually got this article.

Primer

There is a piece of code in the class as follows:

Its general meaning is: the background of the code is to crawl the page url in a multi-threaded network. After the master thread starts, it reads all the urls of the current page from the channel channel, that is, urls, and then crawls to read each url in the urls. The urls in the new page (that is, execute go worker(u, ch, fetcher)), each time a worker thread is started, it starts to write the url to the channel to point to all the urls contained in the page for the master thread to read.

problem thrown

Then the question arises, why does the first layer of for loop not end the loop directly after the range of ch is finished, but also need to use the local variable n to jump out of the loop according to specific situations?

problem explanation

The explanation in the course is that this range will always be blocked, but no explanation is provided. In fact, it is easy to analyze here, because the current channel is an unbuffered channel. The so-called unbuffered channel simply means that two threads operate on the channel, one reads and the other writes, and only one can be written forever, and the other is read in this order. More details

Guess you like

Origin blog.csdn.net/shengyin714959/article/details/130329610