2727#include <string.h>
2828#include <sched.h>
2929#include <sys/types.h>
30+ #ifdef __NetBSD__
31+ #include <sched.h>
32+ #endif
3033
3134/* //////////////////////////////////////////////////////////////////////////////////////
3235 * implementation
@@ -36,7 +39,23 @@ tb_bool_t tb_sched_setaffinity(tb_size_t pid, tb_cpuset_ref_t cpuset)
3639 // check
3740 tb_assert_and_check_return_val (cpuset , tb_false );
3841
39- // set cpu affinity
42+ #ifdef __NetBSD__
43+ // NetBSD uses cpuset_t API for process affinity
44+ cpuset_t * cpu_set = cpuset_create ();
45+ if (!cpu_set )
46+ return tb_false ;
47+
48+ tb_int_t i ;
49+ for (i = 0 ; i < TB_CPUSET_SIZE ; i ++ )
50+ {
51+ if (TB_CPUSET_ISSET (i , cpuset ))
52+ cpuset_set (i , cpu_set );
53+ }
54+ tb_bool_t ok = cpuset_setaffinity (CPU_LEVEL_WHICH , CPU_WHICH_PID , (pid_t )pid , cpuset_size (cpu_set ), cpu_set ) == 0 ;
55+ cpuset_destroy (cpu_set );
56+ return ok ;
57+ #else
58+ // Linux uses cpu_set_t API
4059 tb_int_t i ;
4160 cpu_set_t cpu_set ;
4261 CPU_ZERO (& cpu_set );
@@ -46,13 +65,37 @@ tb_bool_t tb_sched_setaffinity(tb_size_t pid, tb_cpuset_ref_t cpuset)
4665 CPU_SET (i , & cpu_set );
4766 }
4867 return sched_setaffinity ((pid_t )pid , sizeof (cpu_set_t ), & cpu_set ) == 0 ;
68+ #endif
4969}
5070tb_bool_t tb_sched_getaffinity (tb_size_t pid , tb_cpuset_ref_t cpuset )
5171{
5272 // check
5373 tb_assert_and_check_return_val (cpuset , tb_false );
5474
55- // get cpu affinity
75+ #ifdef __NetBSD__
76+ // NetBSD uses cpuset_t API for process affinity
77+ cpuset_t * cpu_set = cpuset_create ();
78+ if (!cpu_set )
79+ return tb_false ;
80+
81+ if (cpuset_getaffinity (CPU_LEVEL_WHICH , CPU_WHICH_PID , (pid_t )pid , cpuset_size (cpu_set ), cpu_set ) != 0 )
82+ {
83+ cpuset_destroy (cpu_set );
84+ return tb_false ;
85+ }
86+
87+ // save cpuset
88+ tb_int_t i ;
89+ TB_CPUSET_ZERO (cpuset );
90+ for (i = 0 ; i < TB_CPUSET_SIZE ; i ++ )
91+ {
92+ if (cpuset_isset (i , cpu_set ))
93+ TB_CPUSET_SET (i , cpuset );
94+ }
95+ cpuset_destroy (cpu_set );
96+ return tb_true ;
97+ #else
98+ // Linux uses cpu_set_t API
5699 cpu_set_t cpu_set ;
57100 CPU_ZERO (& cpu_set );
58101 if (sched_getaffinity ((pid_t )pid , sizeof (cpu_set_t ), & cpu_set ) != 0 )
@@ -67,4 +110,5 @@ tb_bool_t tb_sched_getaffinity(tb_size_t pid, tb_cpuset_ref_t cpuset)
67110 TB_CPUSET_SET (i , cpuset );
68111 }
69112 return tb_true ;
113+ #endif
70114}
0 commit comments