當前位置: 首頁>>代碼示例>>Golang>>正文


Golang runtime.Gosched函數代碼示例

本文整理匯總了Golang中runtime.Gosched函數的典型用法代碼示例。如果您正苦於以下問題:Golang Gosched函數的具體用法?Golang Gosched怎麽用?Golang Gosched使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Gosched函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: TestDumpWithLotsOfMessagesAndLargeBuffer

func TestDumpWithLotsOfMessagesAndLargeBuffer(t *testing.T) {
	var bufferSize uint
	bufferSize = 200
	dump := NewDumpSink("myApp", bufferSize, loggertesthelper.Logger())
	dump.Run()

	for i := 0; i < 1000; i++ {
		logMessage := messagetesthelpers.NewMessage(t, strconv.Itoa(i), "appId")
		dump.Channel() <- logMessage
	}

	runtime.Gosched()

	logMessages := dumpAllMessages(dump, bufferSize)
	assert.Equal(t, len(logMessages), 200)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "800")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "801")

	for i := 1000; i < 2000; i++ {
		logMessage := messagetesthelpers.NewMessage(t, strconv.Itoa(i), "appId")
		dump.Channel() <- logMessage
	}

	runtime.Gosched()

	logMessages = dumpAllMessages(dump, bufferSize)
	assert.Equal(t, len(logMessages), 200)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "1800")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "1801")

	logMessages = dumpAllMessages(dump, bufferSize)
	assert.Equal(t, len(logMessages), 200)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "1800")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "1801")
}
開發者ID:uabassguy,項目名稱:loggregator,代碼行數:35,代碼來源:dump_sink_test.go

示例2: TestConcurrency

func TestConcurrency(t *testing.T) {

	uids := make([]UID, 0)
	results := make(chan UID, MAX)

	// Fire off a number of Goroutines to grab a bunch of UIDs each
	for x := 0; x < LOOPS; x++ {
		go func(results chan UID) {
			for x := 0; x < COUNT_PER_LOOP; x++ {
				results <- <-Next
				runtime.Gosched()
			}
		}(results)
		runtime.Gosched()
	}

	// Wait for results
	for x := 0; x < MAX; x++ {
		uids = append(uids, <-results)
	}

	// Make sure all results are unique
	for x, have := range uids {
		for y, found := range uids {
			if have == found && x != y {
				t.Errorf("Duplicate UID: Cases %d & %d, have %d found %d", x, y, have, found)
			}
		}
	}
}
開發者ID:iaingmackay,項目名稱:simplemud,代碼行數:30,代碼來源:uid_test.go

示例3: TestDumpReturnsAllRecentMessagesToMultipleDumpRequestsWithMessagesCloningInInTheMeantime

func TestDumpReturnsAllRecentMessagesToMultipleDumpRequestsWithMessagesCloningInInTheMeantime(t *testing.T) {
	var bufferSize uint
	bufferSize = 2

	dump := NewDumpSink("myApp", bufferSize, loggertesthelper.Logger())
	dump.Run()

	logMessage := messagetesthelpers.NewMessage(t, "1", "appId")
	dump.Channel() <- logMessage
	logMessage = messagetesthelpers.NewMessage(t, "2", "appId")
	dump.Channel() <- logMessage
	logMessage = messagetesthelpers.NewMessage(t, "3", "appId")
	dump.Channel() <- logMessage

	runtime.Gosched()

	logMessages := dumpAllMessages(dump, bufferSize)
	assert.Equal(t, len(logMessages), 2)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "2")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "3")

	logMessage = messagetesthelpers.NewMessage(t, "4", "appId")
	dump.Channel() <- logMessage

	runtime.Gosched()

	logMessages = dumpAllMessages(dump, bufferSize)
	assert.Equal(t, len(logMessages), 2)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "3")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "4")
}
開發者ID:uabassguy,項目名稱:loggregator,代碼行數:31,代碼來源:dump_sink_test.go

示例4: main

func main() {
	u, err := user.Current()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		// Let the test pass.
		os.Exit(0)
	}

	var wg sync.WaitGroup
	for i := 0; i < 20; i++ {
		wg.Add(2)
		go func() {
			defer wg.Done()
			for i := 0; i < 1000; i++ {
				user.Lookup(u.Username)
				runtime.Gosched()
			}
		}()
		go func() {
			defer wg.Done()
			for i := 0; i < 1000; i++ {
				p := C.malloc(C.size_t(len(u.Username) + 1))
				runtime.Gosched()
				C.free(p)
			}
		}()
	}
	wg.Wait()
}
開發者ID:Greentor,項目名稱:go,代碼行數:29,代碼來源:tsan5.go

示例5: TestDumpWithLotsOfMessagesAndLargeBuffer

func TestDumpWithLotsOfMessagesAndLargeBuffer(t *testing.T) {
	dump := NewDumpSink("myApp", 200, loggertesthelper.Logger(), make(chan Sink, 1), time.Second)

	go dump.Run()

	for i := 0; i < 1000; i++ {
		logMessage := messagetesthelpers.NewMessage(t, strconv.Itoa(i), "appId")
		dump.Channel() <- logMessage
	}

	runtime.Gosched()

	logMessages := dump.Dump()
	assert.Equal(t, len(logMessages), 200)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "800")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "801")

	for i := 1000; i < 2000; i++ {
		logMessage := messagetesthelpers.NewMessage(t, strconv.Itoa(i), "appId")
		dump.Channel() <- logMessage
	}

	runtime.Gosched()

	logMessages = dump.Dump()
	assert.Equal(t, len(logMessages), 200)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "1800")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "1801")

	logMessages = dump.Dump()
	assert.Equal(t, len(logMessages), 200)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "1800")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "1801")
}
開發者ID:james-masson,項目名稱:loggregator,代碼行數:34,代碼來源:dump_sink_test.go

示例6: Manage

// 數據轉儲輸出
func (self *Collector) Manage() {
	// reporter.Log.Println("**************開啟輸出管道************")

	// 標記開始,令self.Ctrl長度不為零
	self.CtrlW()

	// 開啟文件輸出協程
	go self.SaveFile()

	// 隻有當收到退出通知並且通道內無數據時,才退出循環
	for !(self.CtrlLen() == 0 && len(self.DataChan) == 0) {
		// reporter.Log.Println("**************斷點 8 ***********")
		select {
		case data := <-self.DataChan:
			self.dockerOne(data)

		default:
			// time.Sleep(1e7) //0.1秒
			runtime.Gosched()
		}
	}

	// 將剩餘收集到但未輸出的數據輸出
	self.goOutput(self.Curr)

	// 等待所有輸出完成
	for (self.outCount[0] > self.outCount[1]) || (self.outCount[2] > self.outCount[3]) || len(self.FileChan) > 0 {
		// time.Sleep(5e8)
		runtime.Gosched()
	}

	// 返回報告
	self.Report()
}
開發者ID:Cdim,項目名稱:pholcus,代碼行數:35,代碼來源:collector.go

示例7: TestAddPort

func TestAddPort(t *testing.T) {
	l := NewListener()
	gcnt := runtime.NumGoroutine()
	l.AddPort(56561)
	if 1 != len(l.ports) {
		t.Errorf("Length of ports array should be 1, got %d", len(l.ports))
	}
	if runtime.Gosched(); gcnt >= runtime.NumGoroutine() {
		t.Errorf("Expected more than %d goroutines after AddPort, %d running", gcnt, runtime.NumGoroutine())
	}
	if listener, ok := l.ports[56561]; ok {
		if listener == nil {
			t.Errorf("Port listener should not be nil")
		}
	} else {
		t.Errorf("Listener should have entry for port 56561, got %v", l.ports)
	}
	gcnt = runtime.NumGoroutine()
	l.Close()
	if 0 != len(l.ports) {
		t.Errorf("After Close(), ports should have 0 entries, got %d", len(l.ports))
	}
	if runtime.Gosched(); gcnt <= runtime.NumGoroutine() {
		t.Errorf("Expected fewer than %d goroutines after Close(), %d running", gcnt, runtime.NumGoroutine())
	}
}
開發者ID:suapapa,項目名稱:ircd-blight,代碼行數:26,代碼來源:listener_test.go

示例8: listenAction

func (tcp *TcpSer) listenAction() {

	defer func() {
		if err := recover(); err != nil {
			debug.PrintStack()
			glog.Error("handleInput error(%v)", err)
		} else {
		}
	}()

	for {
		conn, err := tcp.listener.Accept()

		if err != nil {
			if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
				log.Printf("NOTICE: temporary Accept() failure - %s", err.Error())
				runtime.Gosched()
				continue
			}
			// theres no direct way to detect this error because it is not exposed
			if !strings.Contains(err.Error(), "use of closed network connection") {
				log.Printf("ERROR: listener.Accept() - %s", err.Error())
			}
			break
		}

		if tcp.ConnCount+1 == tcp.MaxConn {
			glog.Warningf("Too many connections! Active Denial %s\n", conn.RemoteAddr().String())
			conn.Close()
			runtime.Gosched()
			continue
		}
		go tcp.createNewItem(tcp, conn)
	}
}
開發者ID:izouxv,項目名稱:raftX,代碼行數:35,代碼來源:baseSer.go

示例9: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU()) // 모든 CPU 사용

	var data = []int{}
	var mutex = new(sync.Mutex)

	go func() { // 고루틴에서
		for i := 0; i < 1000; i++ { // 1000번 반복하면서
			mutex.Lock()           // 뮤텍스 잠금, data 슬라이스 보호 시작
			data = append(data, 1) // data 슬라이스에 1을 추가
			mutex.Unlock()         // 뮤텍스 잠금 해제, data 슬라이스 보호 종료

			runtime.Gosched() // 다른 고루틴이 CPU를 사용할 수 있도록 양보
		}
	}()

	go func() { // 고루틴에서
		for i := 0; i < 1000; i++ { // 1000번 반복하면서
			mutex.Lock()           // 뮤텍스 잠금, data 슬라이스 보호 시작
			data = append(data, 1) // data 슬라이스에 1을 추가
			mutex.Unlock()         // 뮤텍스 잠금 해제, data 슬라이스 보호 종료

			runtime.Gosched() // 다른 고루틴이 CPU를 사용할 수 있도록 양보
		}
	}()

	time.Sleep(2 * time.Second) // 2초 대기

	fmt.Println(len(data)) // data 슬라이스의 길이 출력
}
開發者ID:jemoonkim,項目名稱:golangbook,代碼行數:30,代碼來源:mutex_2.go

示例10: sleep

func sleep() {
	<-ticker;
	<-ticker;
	runtime.Gosched();
	runtime.Gosched();
	runtime.Gosched();
}
開發者ID:8l,項目名稱:go-learn,代碼行數:7,代碼來源:nonblock.go

示例11: TestDumpWithLotsOfMessages

func TestDumpWithLotsOfMessages(t *testing.T) {
	dump := NewDumpSink("myApp", 2, loggertesthelper.Logger())

	for i := 0; i < 100; i++ {
		logMessage := messagetesthelpers.NewMessage(t, strconv.Itoa(i), "appId")
		dump.Channel() <- logMessage
	}

	runtime.Gosched()

	logMessages := dumpAllMessages(dump)
	assert.Equal(t, len(logMessages), 2)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "98")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "99")

	for i := 100; i < 200; i++ {
		logMessage := messagetesthelpers.NewMessage(t, strconv.Itoa(i), "appId")
		dump.Channel() <- logMessage
	}

	runtime.Gosched()

	logMessages = dumpAllMessages(dump)
	assert.Equal(t, len(logMessages), 2)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "198")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "199")

	logMessages = dumpAllMessages(dump)
	assert.Equal(t, len(logMessages), 2)
	assert.Equal(t, string(logMessages[0].GetLogMessage().GetMessage()), "198")
	assert.Equal(t, string(logMessages[1].GetLogMessage().GetMessage()), "199")
}
開發者ID:pxie,項目名稱:loggregator,代碼行數:32,代碼來源:dump_sink_test.go

示例12: Manage

// 數據轉儲輸出
func (self *Collector) Manage() {
	// 標記開始,令self.Ctrl長度不為零
	self.CtrlW()

	// 開啟文件輸出協程
	go self.SaveFile()

	// 隻有當收到退出通知並且通道內無數據時,才退出循環
	for !(self.CtrlLen() == 0 && len(self.DataChan) == 0) {
		select {
		case data := <-self.DataChan:
			self.Dockers[self.Curr] = append(self.Dockers[self.Curr], data)
			// 檢查是否更換緩存塊
			if len(self.Dockers[self.Curr]) >= cache.Task.DockerCap {
				// curDocker存滿後輸出
				self.goOutput(self.Curr)
				// 更換一個空Docker用於curDocker
				self.DockerQueue.Change()
			}
		default:
			runtime.Gosched()
		}
	}

	// 將剩餘收集到但未輸出的數據輸出
	self.goOutput(self.Curr)

	// 等待所有輸出完成
	for (self.outCount[0] > self.outCount[1]) || (self.outCount[2] > self.outCount[3]) || len(self.FileChan) > 0 {
		runtime.Gosched()
	}

	// 返回報告
	self.Report()
}
開發者ID:ReinhardHsu,項目名稱:pholcus,代碼行數:36,代碼來源:collector.go

示例13: Push

// 添加請求到隊列,並發安全
func (self *Matrix) Push(req *request.Request) {
	if sdl.checkStatus(status.STOP) {
		return
	}

	// 禁止並發,降低請求積存量
	self.Lock()
	defer self.Unlock()

	// 達到請求上限,停止該規則運行
	if self.maxPage >= 0 {
		return
	}

	// 暫停狀態時等待,降低請求積存量
	waited := false
	for sdl.checkStatus(status.PAUSE) {
		waited = true
		runtime.Gosched()
	}
	if waited && sdl.checkStatus(status.STOP) {
		return
	}

	// 資源使用過多時等待,降低請求積存量
	waited = false
	for self.resCount > sdl.avgRes() {
		waited = true
		runtime.Gosched()
	}
	if waited && sdl.checkStatus(status.STOP) {
		return
	}

	// 不可重複下載的req
	if !req.IsReloadable() {
		hash := makeUnique(req)
		// 已存在成功記錄時退出
		if self.hasHistory(hash) {
			return
		}
		// 添加到臨時記錄
		self.insertTempHistory(hash)
	}

	var priority = req.GetPriority()

	// 初始化該蜘蛛下該優先級隊列
	if _, found := self.reqs[priority]; !found {
		self.priorities = append(self.priorities, priority)
		sort.Ints(self.priorities) // 從小到大排序
		self.reqs[priority] = []*request.Request{}
	}

	// 添加請求到隊列
	self.reqs[priority] = append(self.reqs[priority], req)

	// 大致限製加入隊列的請求量,並發情況下應該會比maxPage多
	atomic.AddInt64(&self.maxPage, 1)
}
開發者ID:clock145,項目名稱:pholcus,代碼行數:61,代碼來源:matrix.go

示例14: TestOutputChannel

func TestOutputChannel(t *testing.T) {
	o := &testOutput{}
	oc := NewOutputChannel(o)
	defer oc.Close()
	oc.input <- F{"foo": "bar"}
	assert.Nil(t, o.last)
	runtime.Gosched()
	assert.Equal(t, F{"foo": "bar"}, F(o.last))

	// Trigger error path
	buf := bytes.NewBuffer(nil)
	oldCritialLogger := critialLogger
	defer func() { critialLogger = oldCritialLogger }()
	critialLogger = func(v ...interface{}) {
		fmt.Fprint(buf, v...)
	}
	o.err = errors.New("some error")
	oc.input <- F{"foo": "bar"}
	// Wait for log output to go through
	runtime.Gosched()
	for i := 0; i < 10 && buf.Len() == 0; i++ {
		time.Sleep(10 * time.Millisecond)
	}
	assert.Contains(t, buf.String(), "cannot write log message: some error")
}
開發者ID:patrickToca,項目名稱:xlog,代碼行數:25,代碼來源:output_test.go

示例15: TestClosePort

func TestClosePort(t *testing.T) {
	l := NewListener()
	l.AddPort(56561)
	gcnt := runtime.Goroutines()
	l.ClosePort(56561)
	// ClosePort is not synchronized, so give it some time (on mac, dialog pops up)
	for i := 0; i < 100 && 0 != len(l.ports); i++ {
		time.Sleep(1e6)
	}
	if runtime.Gosched(); 0 != len(l.ports) {
		t.Errorf("After ClosePort(), ports should have 0 entries, got %d", len(l.ports))
	}
	if runtime.Gosched(); gcnt <= runtime.Goroutines() {
		t.Errorf("Expected fewer than %d goroutines after ClosePort(), %d running", gcnt,
			runtime.Goroutines())
	}
	l.Close()
	if 0 != len(l.ports) {
		t.Errorf("After Close(), ports should have 0 entries, got %d", len(l.ports))
	}
	if runtime.Gosched(); gcnt <= runtime.Goroutines() {
		t.Errorf("Expected fewer than %d goroutines after Close(), %d running", gcnt,
			runtime.Goroutines())
	}
}
開發者ID:kylelemons,項目名稱:ircd-blight,代碼行數:25,代碼來源:listener_test.go


注:本文中的runtime.Gosched函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。