Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang的调度机制决定Sleep是用户态实现的。但实现存在一个问题,若go程序在Sleep的过程中系统时间发生变化,Sleep会不准确,因为runtime中的实现是通过时间列表判断每个goroutine的挂起时间,而这个时间就是用的系统时间。这段代码是用cgo调用C的sleep规避这个问题的实现。
package main
/*
#include <unistd.h>
*/
import "C"
import (
"fmt"
"time"
)
func Sleep2(uSeconds uint) {
us := C.__useconds_t(uSeconds)
C.usleep(us)
}
func PrintIt(s string) {
for {
Sleep2(1.5 * 1000 * 1000)
now := time.Now()
fmt.Printf("[%s] %s\n", now, s)
}
}
func main() {
go PrintIt("hello")
go PrintIt("world")
for {
select{}
}
}
@fugr

This comment has been minimized.

Copy link

commented Aug 1, 2013

func main() {
go PrintIt("hello")
go PrintIt("world")
for {
select{} //这样会不会更好?
}
}

@jaypei

This comment has been minimized.

Copy link
Owner Author

commented Aug 19, 2014

是的!Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.