Skip to content

Commit 8ca1179

Browse files
committed
use sys/unix instead of CGO
1 parent b3d9e36 commit 8ca1179

File tree

3 files changed

+10
-21
lines changed

3 files changed

+10
-21
lines changed

affinity_linux.go

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -24,33 +24,18 @@
2424

2525
package gaio
2626

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"
4627
import (
4728
"runtime"
29+
30+
"golang.org/x/sys/unix"
4831
)
4932

5033
// setAffinity binds the current goroutine and its underlying thread to a specific CPU.
5134
// This function locks the goroutine to the current thread, then sets the thread's CPU affinity
5235
// to the specified CPU, which can improve performance by reducing context switching.
5336
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)
5641
}

go.mod

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
module github.com/xtaci/gaio
22

33
go 1.13
4+
5+
require golang.org/x/sys v0.28.0 // indirect

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
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=

0 commit comments

Comments
 (0)