You can use runtime.LockOSThread() to associate the calling goroutine with the current OS thread. This ensures that no other goroutines are assigned to this thread, so your goroutine will work, not be interrupted or delayed. No other goroutines will interfere when the thread is blocked.
After that, you just need a loop until these seconds have passed. You must call runtime.UnlockOSThread() to "free" the thread and make it available to other goroutines to execute, it is best done as a defer .
See this example:
func runUntil(end time.Time) { runtime.LockOSThread() defer runtime.UnlockOSThread() for time.Now().Before(end) { } }
To wait 2 seconds, it might look like this:
start := time.Now() end := start.Add(time.Second * 2) runUntil(end) fmt.Println("Verify:", time.Now().Sub(start))
It is printed, for example:
Verify: 2.0004556s
Of course, you can specify less than a second, for example. to wait 100 ms:
start := time.Now() runUntil(start.Add(time.Millisecond * 100)) fmt.Println("Verify:", time.Now().Sub(start))
Output:
Verify: 100.1278ms
You can use a different version of this function if it suits you, which takes time to "wait" as the value of time.Duration :
func wait(d time.Duration) { runtime.LockOSThread() defer runtime.UnlockOSThread() for end := time.Now().Add(d); time.Now().Before(end); { } }
Using this:
start = time.Now() wait(time.Millisecond * 200) fmt.Println("Verify:", time.Now().Sub(start))
Output:
Verify: 200.1546ms
Note. . Please note that cycles in the above functions will use the CPU ruthlessly, since they do not have sleep or I / O locks, they will simply query the current system time and compare it with the deadline.
What should I do if an attacker increases the system load by several simultaneous attempts?
Go runtime limits the system threads that goroutines can execute at the same time. This is controlled by runtime.GOMAXPROCS() , so this is already a limitation. By default, the number of available processor cores is used, and you can change it at any time. This also creates a bottleneck though, using runtime.LockOSThread() if the number of blocked threads is GOMAXPROCS at any given time, which blocks the execution of other goroutines until the thread is unlocked.
See related questions:
The number of threads used when starting Go
Why does this not create many threads when many goroutines are locked in a file entry in golang?