aboutsummaryrefslogtreecommitdiff
path: root/src/threading_osx.h
blob: c198d6df3a0adbf73c403d5af2e3614533f3e00d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 * THREADING_OSX.H
 * http://yyshen.github.io/2015/01/18/binding_threads_to_cores_osx.html
 */
#pragma once

#include <mach/mach_types.h>
#include <mach/thread_act.h>
#include <sys/sysctl.h>

#define SYSCTL_CORE_COUNT "machdep.cpu.core_count"

struct cpu_set_t
{
	uint32_t count;
} ;

static inline void CPU_ZERO(cpu_set_t *cs) { cs->count = 0; }
static inline void CPU_SET(int num, cpu_set_t *cs) { cs->count |= (1 << num); }
[[nodiscard]]
static inline int CPU_ISSET(int num, cpu_set_t *cs) { return (cs->count & (1 << num)); }

[[nodiscard]]
int sched_getaffinity(pid_t pid, size_t cpu_size, cpu_set_t *cpu_set)
{
	int32_t core_count = 0;
	size_t  len = sizeof(core_count);
	int ret = sysctlbyname(SYSCTL_CORE_COUNT, &core_count, &len, 0, 0);
	if (ret)
	{
//		printf("error while get core count %d\n", ret);
		return -1;
	}
	cpu_set->count = 0;
	for (int i = 0; i < core_count; i++)
	{
		cpu_set->count |= (1 << i);
	}

	return 0;
}

[[nodiscard]]
int pthread_setaffinity_np(pthread_t thread, size_t cpu_size, cpu_set_t *cpu_set)
{
	thread_port_t mach_thread;
	int core = 0;

	for (core = 0; core < 8 * cpu_size; core++)
	{
		if (CPU_ISSET(core, cpu_set))
			break;
	}
//	printf("binding to core %d\n", core);
	thread_affinity_policy_data_t policy = { core };
	mach_thread = pthread_mach_thread_np(thread);
	thread_policy_set(mach_thread, THREAD_AFFINITY_POLICY, (thread_policy_t)&policy, 1);

	return 0;
}