当前位置: 首页>>代码示例>>Golang>>正文


Golang runtime.NumGoroutine函数代码示例

本文整理汇总了Golang中runtime.NumGoroutine函数的典型用法代码示例。如果您正苦于以下问题:Golang NumGoroutine函数的具体用法?Golang NumGoroutine怎么用?Golang NumGoroutine使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NumGoroutine函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestChan3

func TestChan3() {
	fmt.Println("@@@@@@@@@@@@ TestChan 3")

	fmt.Printf("cpu num: %d\n", runtime.NumCPU()) // 8核cpu

	// 虽然goroutine是并发执行的,但是它们并不是并行运行的。如果不告诉Go额外的东西,同
	// 一时刻只会有一个goroutine执行。利用runtime.GOMAXPROCS(n)可以设置goroutine
	// 并行执行的数量。GOMAXPROCS 设置了同时运行的CPU 的最大数量,并返回之前的设置。
	val := runtime.GOMAXPROCS(runtime.NumCPU() * 4)
	fmt.Printf("last goroutine num: %d\n", val) // 8个

	fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 4个goroutine同时运行

	var ch1 chan int = make(chan int, 0)
	var ch2 chan int = make(chan int, 0)
	var ch3 chan int = make(chan int, 0)

	go write(ch1, 22)
	go write(ch2, 33)
	go write(ch3, 44)
	go read(ch1)
	go read(ch2)
	go read(ch3)

	fmt.Printf("goroutine num: %d\n", runtime.NumGoroutine()) // 10个goroutine同时运行
	sleep("TestChan3", 3)
}
开发者ID:47045039,项目名称:GoSnippet,代码行数:27,代码来源:tch.go

示例2: TestParallelSimple

func TestParallelSimple(t *testing.T) {
	On("p-1", func() {
		for i := 1; i <= 10000; i++ {

		}
	})

	On("p-2", func() {
		for i := 1; i <= 10000; i++ {

		}
	})
	prev := runtime.NumGoroutine()
	FireBackground("p-1")
	FireBackground("p-2")
	FireBackground("p-2")
	FireBackground("p-2")
	FireBackground("p-2")
	FireBackground("p-2")
	FireBackground("p-2")
	FireBackground("p-2")

	now := runtime.NumGoroutine()
	fmt.Println("Number of go routine running ", now-prev)
	Equal(t, 8, now-prev)
	ClearEvents()
}
开发者ID:faide,项目名称:go-trigger,代码行数:27,代码来源:trigger_test.go

示例3: main

func main() {
	fmt.Println("Please wait....")
	URL := flag.String("i", "https://127.0.0.1/", "dst server URL")
	num := flag.Int("n", 1, "process num")
	loop := flag.Bool("l", false, "loop flag")
	ecdh := flag.Bool("e", false, "ecdh flag")
	show := flag.Bool("s", false, "show body flag")
	flag.Parse()
	result := make(chan int)
	//通信結果を受け取るためのプロセス
	go recieving(result, *loop, *num)

	t := time.Now()
	for i := 0; i < *num; i++ { //通信プロセスの作成
		go connect(*URL, i, *loop, *show, *ecdh, result)
	}
	f := time.Now()
	//通信プロセスの作成時間
	fmt.Println("Create process time: ", f.Sub(t))
	//現在動いてるプロセス数
	fmt.Println("Current Process num: ", runtime.NumGoroutine())
	//mainプロセスを待機させておく
	time.Sleep(3 * time.Second) //プロセス作成時間分待機
	//プロセスが残ってるうちは待機
	for runtime.NumGoroutine() > 4 || *loop {
		time.Sleep(1 * time.Second)
	}
	//終了時のプロセス数
	fmt.Println("Current Process num: ", runtime.NumGoroutine())
}
开发者ID:yatuhashi,项目名称:SSLGOMI,代码行数:30,代码来源:htlc.go

示例4: TestQueueConsumerRunStopsGracefullyWhenCancelled

func TestQueueConsumerRunStopsGracefullyWhenCancelled(t *testing.T) {
	// log to /dev/null because the deleter is chatty
	log.SetOutput(ioutil.Discard)
	defer func() {
		log.SetOutput(os.Stderr)
	}()

	ctl := gomock.NewController(t)
	defer ctl.Finish()

	// delay so that the cancel occurs mid-receive
	delay := func(x interface{}) {
		time.Sleep(10 * time.Millisecond)
	}
	m := mock.NewMockSQSAPI(ctl)
	m.EXPECT().ReceiveMessage(gomock.Any()).Do(delay).Return(&sqs.ReceiveMessageOutput{}, nil).AnyTimes()
	m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil)
	m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes()

	s := &SQSService{Svc: m}
	q := NewConsumer(s, noop)
	q.delayAfterReceiveError = time.Millisecond

	ngo := runtime.NumGoroutine()

	// wait long enough to ensure ReceiveMessage is running
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Millisecond)
	err := q.Run(ctx)

	assert.Error(t, err)

	time.Sleep(time.Millisecond) // time for goroutines to end
	assert.InDelta(t, ngo, runtime.NumGoroutine(), 2, "Should not leak goroutines")
}
开发者ID:Wattpad,项目名称:sqsconsumer,代码行数:34,代码来源:queue_consumer_test.go

示例5: TestGoroutineLeak

// For issue 1791
func (s *testTableCodecSuite) TestGoroutineLeak(c *C) {
	var sr SelectResult
	countBefore := runtime.NumGoroutine()

	sr = &selectResult{
		resp:    &mockResponse{},
		results: make(chan PartialResult, 5),
		done:    make(chan error, 1),
		closed:  make(chan struct{}),
	}
	go sr.Fetch()
	for {
		// mock test will generate some partial result then return error
		_, err := sr.Next()
		if err != nil {
			// close selectResult on error, partialResult's fetch goroutine may leak
			sr.Close()
			break
		}
	}

	tick := 10 * time.Millisecond
	totalSleep := time.Duration(0)
	for totalSleep < 3*time.Second {
		time.Sleep(tick)
		totalSleep += tick
		countAfter := runtime.NumGoroutine()

		if countAfter-countBefore < 5 {
			return
		}
	}

	c.Error("distsql goroutine leak!")
}
开发者ID:jmptrader,项目名称:tidb,代码行数:36,代码来源:distsql_test.go

示例6: TestStartStop

func TestStartStop(t *testing.T) {
	assert := assert.New(t)

	startGoroutineNum := runtime.NumGoroutine()

	for i := 0; i < 10; i++ {
		qa.Root(t, func(root string) {
			configFile := TestConfig(root)

			app := carbon.New(configFile)

			assert.NoError(app.ParseConfig())
			assert.NoError(app.Start())

			app.Stop()
		})
	}

	endGoroutineNum := runtime.NumGoroutine()

	// GC worker etc
	if !assert.InDelta(startGoroutineNum, endGoroutineNum, 3) {
		p := pprof.Lookup("goroutine")
		p.WriteTo(os.Stdout, 1)
	}

}
开发者ID:xyntrix,项目名称:go-carbon,代码行数:27,代码来源:app_stop_test.go

示例7: TestClient

func TestClient(t *testing.T) {
	log.Println("----------------TestClient begins----------------")
	cli, err := NewClient(s)

	if err != nil {
		t.Fatal(err)
	}

	if err = cli.Connect(); err != nil {
		t.Fatal(err)
	}
	n := runtime.NumGoroutine()
	go cli.Spin()
	if n == runtime.NumGoroutine() {
		t.Fatalf("no goroutine created!!!")
	}
	time.Sleep(10 * time.Second)
	cli.Stop()
	time.Sleep(2 * time.Second) // let goroutines die
	log.Println("stopped spinning")
	if n != runtime.NumGoroutine() {
		t.Fatalf("%d goroutines still running!!!", runtime.NumGoroutine()-n)
	}
	log.Println("----------------TestClient ends----------------")
}
开发者ID:zxjcarrot,项目名称:egoirc,代码行数:25,代码来源:cli_test.go

示例8: TestRecvChanLeakGoRoutines

func TestRecvChanLeakGoRoutines(t *testing.T) {
	s := RunDefaultServer()
	defer s.Shutdown()

	ec := NewEConn(t)
	defer ec.Close()

	// Call this to make sure that we have everything setup connection wise
	ec.Flush()

	before := runtime.NumGoroutine()

	ch := make(chan int)

	sub, err := ec.BindRecvChan("foo", ch)
	if err != nil {
		t.Fatalf("Failed to bind to a send channel: %v\n", err)
	}
	sub.Unsubscribe()

	// Sleep a bit to wait for the Go routine to exit.
	time.Sleep(500 * time.Millisecond)

	delta := (runtime.NumGoroutine() - before)

	if delta > 0 {
		t.Fatalf("Leaked Go routine(s) : %d, closing channel should have closed them\n", delta)
	}
}
开发者ID:nats-io,项目名称:nats,代码行数:29,代码来源:netchan_test.go

示例9: TestRecvChanAsyncLeakGoRoutines

func TestRecvChanAsyncLeakGoRoutines(t *testing.T) {
	ec := NewEConn(t)
	defer ec.Close()

	before := runtime.NumGoroutine()

	ch := make(chan int)

	if _, err := ec.BindRecvChan("foo", ch); err != nil {
		t.Fatalf("Failed to bind to a send channel: %v\n", err)
	}

	// Close the receive Channel
	close(ch)

	// The publish will trugger the close and shutdown of the Go routines
	ec.Publish("foo", 22)
	ec.Flush()

	time.Sleep(50 * time.Millisecond)

	after := runtime.NumGoroutine()

	if before != after {
		t.Fatalf("Leaked Go routine(s) : %d, closing channel should have closed them\n", after-before)
	}
}
开发者ID:lucmichalski,项目名称:crawler,代码行数:27,代码来源:netchan_test.go

示例10: main

func main() {
	fmt.Println("Please wait 5s....")
	ip := flag.String("i", "127.0.0.1:443", "dst server ip address(default 127.0.0.1:443)")
	num := flag.Int("n", 1, "process num")
	loop := flag.Bool("l", false, "loop flag")
	flag.Parse()
	result := make(chan int)

	go recieving(result, *loop, *num)

	t := time.Now()
	for i := 0; i < *num; i++ { //通信プロセスの作成
		go loopconnection(*ip, i, *loop, result)
	}
	f := time.Now()
	//通信プロセスの作成時間
	fmt.Println("Create process time: ", f.Sub(t))
	//現在動いてるプロセス数
	fmt.Println("Current Process num: ", runtime.NumGoroutine())
	//mainプロセスを待機させておく
	time.Sleep(3 * time.Second)
	for runtime.NumGoroutine() > 2 {
		time.Sleep(1 * time.Second)
		fmt.Println("Current Process num: ", runtime.NumGoroutine())
	}
}
开发者ID:yatuhashi,项目名称:SSLGOMI,代码行数:26,代码来源:Ctls.go

示例11: TestRecvChanAsyncLeakGoRoutines

func TestRecvChanAsyncLeakGoRoutines(t *testing.T) {
	s := RunDefaultServer()
	defer s.Shutdown()

	ec := NewEConn(t)
	defer ec.Close()

	// Call this to make sure that we have everything setup connection wise
	ec.Flush()

	before := runtime.NumGoroutine()

	ch := make(chan int)

	if _, err := ec.BindRecvChan("foo", ch); err != nil {
		t.Fatalf("Failed to bind to a send channel: %v\n", err)
	}

	// Close the receive Channel
	close(ch)

	// The publish will trigger the close and shutdown of the Go routines
	ec.Publish("foo", 22)
	ec.Flush()

	time.Sleep(100 * time.Millisecond)

	delta := (runtime.NumGoroutine() - before)

	if delta > 0 {
		t.Fatalf("Leaked Go routine(s) : %d, closing channel should have closed them\n", delta)
	}
}
开发者ID:nats-io,项目名称:nats,代码行数:33,代码来源:netchan_test.go

示例12: TestCloseLeakingGoRoutines

func TestCloseLeakingGoRoutines(t *testing.T) {
	s := RunDefaultServer()
	defer s.Shutdown()

	// Give time for things to settle before capturing the number of
	// go routines
	time.Sleep(500 * time.Millisecond)

	base := runtime.NumGoroutine()

	nc := NewDefaultConnection(t)

	nc.Flush()
	nc.Close()

	// Give time for things to settle before capturing the number of
	// go routines
	time.Sleep(500 * time.Millisecond)

	delta := (runtime.NumGoroutine() - base)
	if delta > 0 {
		t.Fatalf("%d Go routines still exist post Close()", delta)
	}
	// Make sure we can call Close() multiple times
	nc.Close()
}
开发者ID:quixoten,项目名称:nats,代码行数:26,代码来源:basic_test.go

示例13: TestActiveClose

func TestActiveClose(t *testing.T) {
	go func() {
		log.Println(http.ListenAndServe("localhost:6060", nil))
	}()
	s := New()
	s.RegCb(&testcb{s})

	p := make([]runtime.StackRecord, 100)
	fn, _ := runtime.GoroutineProfile(p)
	Println(p[:fn])
	Println("runtime.NumGoroutine()", runtime.NumGoroutine())

	connid, err := s.ConnectBlock("10.1.9.34:9889", time.Second*10)
	if err != nil {
		return
	}
	time.Sleep(time.Second * 50)
	fn, _ = runtime.GoroutineProfile(p)
	Println(p[:fn])
	Println("runtime.NumGoroutine()", runtime.NumGoroutine())

	s.CloseConn(connid)

	time.Sleep(time.Second * 50)
	fn, _ = runtime.GoroutineProfile(p)
	Println(p[:fn])
	Println("runtime.NumGoroutine()", runtime.NumGoroutine())
}
开发者ID:2qif49lt,项目名称:golang,代码行数:28,代码来源:srv_test.go

示例14: parallel_Traspose

func (this *Matrix) parallel_Traspose(i0, i1, j0, j1 int, res *Matrix, done chan<- bool, conjugate bool) {
	di := i1 - i0
	dj := j1 - j0
	done2 := make(chan bool, THRESHOLD)
	if di >= dj && di >= THRESHOLD && runtime.NumGoroutine() < maxGoRoutines {
		mi := i0 + di/2
		go this.parallel_Traspose(i0, mi, j0, j1, res, done2, conjugate)
		this.parallel_Traspose(mi, i1, j0, j1, res, done2, conjugate)
		<-done2
		<-done2
	} else if dj >= THRESHOLD && runtime.NumGoroutine() < maxGoRoutines {
		mj := j0 + dj/2

		go this.parallel_Traspose(i0, i1, j0, mj, res, done2, conjugate)
		this.parallel_Traspose(i0, i1, mj, i1, res, done2, conjugate)
		<-done2
		<-done2
	} else {

		if !conjugate {
			for i := i0; i <= i1; i++ {
				for j := j0; j <= j1; j++ {
					res.SetValue(j, i, this.GetValue(i, j))
				}
			}
		} else {
			for i := i0; i <= i1; i++ {
				for j := j0; j <= j1; j++ {
					res.SetValue(j, i, cmplx.Conj(this.GetValue(i, j)))
				}
			}
		}
	}
	done <- true
}
开发者ID:eddytrex,项目名称:AIgo,代码行数:35,代码来源:Arithmetic.go

示例15: main

func main() {
	fmt.Println(runtime.NumGoroutine())
	//runtime.GOMAXPROCS(1)

	//生成随机种子
	rand.Seed(time.Now().Unix())

	begin := make(chan bool)
	go busy(begin)
	fmt.Println(runtime.NumGoroutine())
	<-begin
	fmt.Println("is fucking!")

	var input string
	fmt.Scanln(&input)

	fmt.Println("done1")

	var name string
	for i := 0; i < 3; i++ {
		name = fmt.Sprintf("go_%02d", i) //生成ID
		//生成随机等待时间,从0-4秒
		go routine(name, time.Duration(rand.Intn(5))*time.Second)
	}

	fmt.Println(runtime.NumGoroutine())
	//让主进程停住,不然主进程退了,goroutine也就退了

	fmt.Scanln(&input)
	fmt.Println("done")
	fmt.Println(runtime.NumGoroutine())
}
开发者ID:shawnfeng,项目名称:code_tst,代码行数:32,代码来源:hello.go


注:本文中的runtime.NumGoroutine函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。