【问题标题】:In which place interrupts can interrupt function in C?在 C 语言中,中断可以在哪些地方中断功能?
【发布时间】:2015-10-26 23:14:05
【问题描述】:

我正在使用 ISO C90 编写代码,它禁止混合声明和代码。 所以我有这样的事情:

int function(int something)
{
    int foo, ret;
    int bar = function_to_get_bar();
    some_typedef_t foobar = get_this_guy(something);

    spin_lock_irqsave(lock);

    /*
    Here is code that does a lot of things
    */

    spin_unlock_irqrestore(lock);

    return ret;
}

问题是硬件中断还是软件中断,在什么地方可以中断我的函数,也可以在变量声明的中间发生吗?

我问这个是因为我需要这个函数不被中断打断。我想使用 spin_lock_irqsave() 来确保这一点,但我想知道中断是否会在变量声明中中断我的函数?

【问题讨论】:

    标签: c linux-kernel interrupt-handling spinlock


    【解决方案1】:

    中断是高度特定于硬件平台的。但是处理器运行的代码中没有“变量声明”。变量只是预先确定的内存(或寄存器,如果编译器选择的话)中的位置。

    如果您的意思是分配给变量,那么是的,通常会发生中断。如果您需要 function_to_get_bar() 不被打断并且spin_lock_irqsave(lock); 保证不会被打断,那么只需将分配移到其中。

    int function(int something)
    {
        int foo, ret;
        int bar; // This is declaration, just for the compiler
        some_typedef_t foobar;
    
        spin_lock_irqsave(lock);
    
        bar = function_to_get_bar(); // This is assignment, will actually run some code on the CPU
        foobar = get_this_guy(something);
    
        /*
        Here is code that does a lot of things
        */
    
        spin_unlock_irqrestore(lock);
    
        return ret;
    }
    

    【讨论】:

    • 这回答了我的问题。谢谢
    • @PaulOgilvie 当然会在进入锁之前完成,但这不是重点。这些值来自函数,并且在调用它们时可能会发生中断,除非被锁定。中断可能会影响函数的结果。
    • 附带说明:在 SMP 系统上,中断仍会到达其余 CPU,但在此特定 CPU 上运行的代码不会被中断。而且我们必须记住(特别是在像 1)spin_lock()、2)do_smth()、3)spin_unlock() 和 4)return 这样的函数中)我们保护数据访问,而不是代码本身!
    猜你喜欢
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多