golang 去并发测试(我学习去)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 去并发测试(我学习去)相关的知识,希望对你有一定的参考价值。

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("Concurrency test")

    concurrency := 5
    workers := make(chan bool, concurrency)

    // Ensure each worker is set to true (ready)
    for i := 0; i < cap(workers); i++ {
        select {
            default:
                workers <- true
        }
    }

    // i is purely for output reasons
    for i := 0; ; i++ {
        select {
            case <-workers:
                output := make(chan string)

                go func(w chan bool) {
                    defer func() {
                        w <- true
                    }()

                    output <- fmt.Sprintf("request %d", i)
                    time.Sleep(1000 * time.Millisecond)
                }(workers)

                fmt.Println(<-output)
        }
    }
}

golang 去并发模式:只让一个线程做关键事情,其他线程等待并通过工作。

package main

import (
	"log"
	"sync"
	"time"
)

var flag bool
var wg sync.WaitGroup

func One() {
	if flag {
		wg.Wait()
	} else {
		flag = true
		wg.Add(1)
		log.Println("I am doing!")
		// do some thing only one can do at one time
		time.Sleep(5 * time.Second)
		log.Println("DONE!!")
		wg.Done()

		// let others come in the nearest time period pass this action
		go func() {
			// as long as req timeout
			time.Sleep(5 * time.Second)
			flag = false
			log.Println("next period")
		}()
	}
	log.Println("op!")
}

func main() {
	flag = false
	for i := 0; i < 10; i++ {
		time.Sleep(1 * time.Second)
		go One()
	}
	time.Sleep(2 * time.Second)
	log.Println("try again!")
	for i := 0; i < 10; i++ {
		time.Sleep(1 * time.Second)
		go One()
	}
	time.Sleep(2 * time.Second)
	log.Println("main end!")
}

以上是关于golang 去并发测试(我学习去)的主要内容,如果未能解决你的问题,请参考以下文章

golang学习笔记6——并发

golang学习随便记12

golang 去并发模式:只让一个线程做关键事情,其他线程等待并通过工作。

golang 使用去并发下载图片资源来源:HTTP://my.oschina.net/qbit/blog/189928

golang 我正在努力学习去讨厌自己

Golang 并发读写map安全问题详解