Skip to content

Instantly share code, notes, and snippets.

@jaypei
Last active July 17, 2023 06:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jaypei/5334115 to your computer and use it in GitHub Desktop.
Save jaypei/5334115 to your computer and use it in GitHub Desktop.
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
Copy link

fugr commented Aug 1, 2013

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

@jaypei
Copy link
Author

jaypei commented Aug 19, 2014

是的!Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment