C 使代码在多处理器上运行一次

C 使代码在多处理器上运行一次,c,C,我想要实现的伪代码: //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 } 问题是,当我将start irq发送到所有DSP(包括id 0)时,我

我想要实现的伪代码:

//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
}

问题是,当我将start irq发送到所有DSP(包括id 0)时,我多次在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
是您的布尔变量。顺便说一下,您不能只写
alreadyRun=true
,因为如果处理器设置的缓存未刷新回主存,则无法保证其他处理器会看到更改。线程库将具有适当的函数来执行互斥锁并安全地设置alreadyRun。例如,C11在
stdatomic.h
中定义了标记和互斥函数中的原子类型和操作,在
threads.h

中,目前我不清楚。你能详细说明一下吗?我不能添加MCVE,因为它是机密的。我的第一种方法是将标志写入外部内存,但我发现它既慢又难看,这种方法更快更合适。谢谢!