警告
本文最后更新于 2022-09-13,文中内容可能已过时。
在 C++ std::thread
创建的时候,绑定 cpu
核。
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
|
//先申明一个 thread
std::thread _thr;
#define FOR_EACH_ALGO(FUNC) \
for (auto& e : _symbols) \
{ \
auto single_eng = e.second.get(); \
for (auto& exec : single_eng->algos()) \
{ \
auto algo = reinterpret_cast<exec_algo_cv_alpha_t*>(exec); \
algo->FUNC(_ac); \
} \
}
std::thread(
[this]()
{
const auto& cfg = _shell->conf();
if (cfg.has("auction_cpu"))
{
int cpuid = std::stoi(cfg("auction_cpu"));
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(cpuid, &cpuset);
int rtn = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
if (rtn != 0)
L_err("fail to call pthread_setaffinity_np, error rtn:", rtn);
else
L_inf("succ to call pthread_setaffinity_np");
DBG({
print_cpu_affinity(cpuid);
})
}
while (true)
{
_ac.ntime = to_ntime(microtime().now().count());
if (_ac.ntime > _ac.end_ntime + 10)
{
FOR_EACH_ALGO(on_auction_deactivate)
break;
}
if (_ac.ntime >= _ac.insert_ntime && _ac.ntime <= _ac.end_ntime && !_ac.is_triggered)
{
_ac.is_triggered = true;
FOR_EACH_ALGO(on_auction_activate)
}
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
L_inf("end of engine thread, ntime:", _ac.ntime);
}).swap(_thr);
// 从主线程分离
_thr.detach();
// 在析构停止
if (_thr.joinable())
_thr.join();
|
有一个小工具可以查看是否绑核成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
void print_cpu_affinity(int coreid)
{
cpu_set_t mask;
long nproc;
if (::sched_getaffinity(0, sizeof(cpu_set_t), &mask) == -1)
{
L_inf("fail to sched_getaffinity:", coreid);
}
nproc = sysconf(_SC_NPROCESSORS_ONLN);
if (coreid < 0)
{
for (int i = 0; i < nproc; i++)
L_inf("cpu afffinity core:", i, ", is_set:", CPU_ISSET(i, &mask));
}
else
{
L_inf("cpu afffinity core:", coreid, ", is_set:", CPU_ISSET(coreid, &mask));
}
}
|