gpt4 book ai didi

c - 让代码在多处理器上运行一次

转载 作者:行者123 更新时间:2023-11-30 14:57:39 26 4
gpt4 key购买 nike

我想要完成的伪代码:

//gets current running digital singal processor
int dsp_id = get_dsp_id();
if (dsp_id == 0) {
//code run only once
//irq start all other dsps including dsp_id 0
} else {
//code run multiple times
}

问题是当我向包括 id 0 在内的所有 dsp 发送 start irq 时,我一遍又一遍地进入 if 语句,我试图用全局静态 bool 来标记它,但这不起作用。

最佳答案

你有竞争条件。我想您启动的其他线程在设置全局变量之前会命中 if 语句。您需要使用互斥锁来保护锁。在伪代码中,这将类似于

if (dsp_id == 0) {
get mutex lock
if (!alreadyRun)
{
//code run only once
//irq start all other dsps including dsp_id 0
set alreadyRun to true
}
release mutex lock
} else {
//code run multiple times
}

其中alreadyRun是您的 bool 变量。顺便说一句,您不能只写 alreadyRun = true 因为如果处理器设置的缓存尚未刷新回主内存,则不能保证其他处理器会看到更改。您的线程库将具有适当的函数来执行互斥锁并安全地设置alreadyRun。例如,C11 在 stdatomic.h 中为 threads.h

中的标志和互斥函数定义原子类型和操作

关于c - 让代码在多处理器上运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43756437/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com