Golang

 1// A map of registered matchers for searching.
 2var matchers = make(map[string]Matcher)
 3
 4// Run performs the search logic.
 5func Run(searchTerm string) {
 6	// Retrieve the list of feeds to search through.
 7	feeds, err := RetrieveFeeds()
 8	if err != nil {
 9		log.Fatal(err)
10	}
11
12	// Create an unbuffered channel to receive match results to display.
13	results := make(chan *Result)
14
15	// Setup a wait group so we can process all the feeds.
16	var waitGroup sync.WaitGroup
17
18	// Set the number of goroutines we need to wait for while
19	// they process the individual feeds.
20	waitGroup.Add(len(feeds))
21
22	// Launch a goroutine for each feed to find the results.
23	for _, feed := range feeds {
24		// Retrieve a matcher for the search.
25		matcher, exists := matchers[feed.Type]
26		if !exists {
27			matcher = matchers["default"]
28		}
29
30		// Launch the goroutine to perform the search.
31		go func(matcher Matcher, feed *Feed) {
32			Match(matcher, feed, searchTerm, results)
33			waitGroup.Done()
34		}(matcher, feed)
35	}
36
37	// Launch a goroutine to monitor when all the work is done.
38	go func() {
39		// Wait for everything to be processed.
40		waitGroup.Wait()
41
42		// Close the channel to signal to the Display
43		// function that we can exit the program.
44		close(results)
45	}()
46
47	// Start displaying results as they are available and
48	// return after the final result is displayed.
49	Display(results)
50}
51
52// Register is called to register a matcher for use by the program.
53func Register(feedType string, matcher Matcher) {
54	if _, exists := matchers[feedType]; exists {
55		log.Fatalln(feedType, "Matcher already registered")
56	}
57
58	log.Println("Register", feedType, "matcher")
59	matchers[feedType] = matcher
60}
  1. 通过Register()方法更新 matchers

  2. wg.Wait() 如果wg.Add(n)没有完成对应的wg.Done()就会一直hang在这里

  3. for v:=range chan 只要chan没有关闭,就会一直hang在这里

  4. Display()这样用会不会易读一点

     1	// Start displaying results as they are available and
     2	// return after the final result is displayed.
     3	go Display(results)
     4
     5	// Wait for everything to be processed.
     6	waitGroup.Wait()
     7
     8	// Close the channel to signal to the Display
     9	// function that we can exit the program.
    10	close(results)