File tree Expand file tree Collapse file tree 3 files changed +10
-21
lines changed Expand file tree Collapse file tree 3 files changed +10
-21
lines changed Original file line number Diff line number Diff line change 24
24
25
25
package gaio
26
26
27
- /*
28
- #define _GNU_SOURCE
29
- #include <sched.h>
30
- #include <pthread.h>
31
-
32
- // lock_thread sets the CPU affinity for the calling thread to the specified CPU.
33
- // This ensures that the thread runs only on the designated CPU, which can help
34
- // with performance optimization and consistent execution timing on multi-core systems.
35
- void lock_thread(int cpuid) {
36
- pthread_t tid;
37
- cpu_set_t cpuset;
38
-
39
- tid = pthread_self(); // Get the ID of the calling thread
40
- CPU_ZERO(&cpuset); // Initialize the CPU set to be empty
41
- CPU_SET(cpuid, &cpuset); // Add the specified CPU to the set
42
- pthread_setaffinity_np(tid, sizeof(cpu_set_t), &cpuset); // Set the thread's CPU affinity
43
- }
44
- */
45
- import "C"
46
27
import (
47
28
"runtime"
29
+
30
+ "golang.org/x/sys/unix"
48
31
)
49
32
50
33
// setAffinity binds the current goroutine and its underlying thread to a specific CPU.
51
34
// This function locks the goroutine to the current thread, then sets the thread's CPU affinity
52
35
// to the specified CPU, which can improve performance by reducing context switching.
53
36
func setAffinity (cpuId int32 ) {
54
- runtime .LockOSThread () // Lock the current goroutine to its current thread
55
- C .lock_thread (C .int (cpuId )) // Set the thread's CPU affinity to the specified CPU
37
+ var newMask unix.CPUSet
38
+ newMask .Set (int (cpuId ))
39
+ runtime .LockOSThread () // Lock the current goroutine to its current thread
40
+ _ = unix .SchedSetaffinity (0 , & newMask )
56
41
}
Original file line number Diff line number Diff line change 1
1
module github.com/xtaci/gaio
2
2
3
3
go 1.13
4
+
5
+ require golang.org/x/sys v0.28.0 // indirect
Original file line number Diff line number Diff line change
1
+ golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA =
2
+ golang.org/x/sys v0.28.0 /go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA =
You can’t perform that action at this time.
0 commit comments