Last active
July 17, 2023 06:26
-
-
Save jaypei/5334115 to your computer and use it in GitHub Desktop.
Golang的调度机制决定Sleep是用户态实现的。但实现存在一个问题,若go程序在Sleep的过程中系统时间发生变化,Sleep会不准确,因为runtime中的实现是通过时间列表判断每个goroutine的挂起时间,而这个时间就是用的系统时间。这段代码是用cgo调用C的sleep规避这个问题的实现。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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{} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
func main() {
go PrintIt("hello")
go PrintIt("world")
for {
select{} //这样会不会更好?
}
}