當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。