Skip to content

Commit

Permalink
use sys/unix instead of CGO
Browse files Browse the repository at this point in the history
  • Loading branch information
xtaci committed Dec 20, 2024
1 parent b3d9e36 commit 8ca1179
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 21 deletions.
27 changes: 6 additions & 21 deletions affinity_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,33 +24,18 @@

package gaio

/*
#define _GNU_SOURCE
#include <sched.h>
#include <pthread.h>
// lock_thread sets the CPU affinity for the calling thread to the specified CPU.
// This ensures that the thread runs only on the designated CPU, which can help
// with performance optimization and consistent execution timing on multi-core systems.
void lock_thread(int cpuid) {
pthread_t tid;
cpu_set_t cpuset;
tid = pthread_self(); // Get the ID of the calling thread
CPU_ZERO(&cpuset); // Initialize the CPU set to be empty
CPU_SET(cpuid, &cpuset); // Add the specified CPU to the set
pthread_setaffinity_np(tid, sizeof(cpu_set_t), &cpuset); // Set the thread's CPU affinity
}
*/
import "C"
import (
"runtime"

"golang.org/x/sys/unix"
)

// setAffinity binds the current goroutine and its underlying thread to a specific CPU.
// This function locks the goroutine to the current thread, then sets the thread's CPU affinity
// to the specified CPU, which can improve performance by reducing context switching.
func setAffinity(cpuId int32) {
runtime.LockOSThread() // Lock the current goroutine to its current thread
C.lock_thread(C.int(cpuId)) // Set the thread's CPU affinity to the specified CPU
var newMask unix.CPUSet
newMask.Set(int(cpuId))
runtime.LockOSThread() // Lock the current goroutine to its current thread
_ = unix.SchedSetaffinity(0, &newMask)
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module github.com/xtaci/gaio

go 1.13

require golang.org/x/sys v0.28.0 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

0 comments on commit 8ca1179

Please sign in to comment.