代码之家  ›  专栏  ›  技术社区  ›  Amir Zadeh

sig_atomic_t在Linux信号屏蔽函数中的应用

  •  2
  • Amir Zadeh  · 技术社区  · 15 年前

    我最近在研究一本叫做高级Linux编程的书,我遇到了一个问题:书上说你应该使用 sig_atomic_t 变量类型,以确保如果在信号处理程序函数中设置全局标志或计数器,则在算术运算(即 ++ )把它们存到登记簿里。

    我的问题是:如果我们不使用 西格玛 只是使用另一种类型和上下文切换发生了吗?我的意思是程序稍后会返回并保存它。有人能给我一个让我们的代码不稳定或有缺陷的场景吗?

    3 回复  |  直到 13 年前
        1
  •  2
  •   Bart van Ingen Schenau    15 年前

    main context:
      read i (=10) from memory to register R1
      add 5 to R1
        <interrupt. Switch to interrupt context>
        read i (=10) from memory to register R1
        add 10 to R1
        write R1 to i in memory (i = 20)
        <end of interrupt. Back to main context>
      write R1 to i in memory (i = 15)
    

    main context:
      read first half of i (=10) from memory to register R1
      read second half of i (=10) from memory to register R2
      add 5 to R1/R2 pair
      write R1 to first half of i in memory
        <interrupt. Switch to interrupt context>
        read first half of i (= ??) from memory to register R1
        read second half of i (= ??) from memory to register R2
        add 10 to R1/R2 pair
        write R1 to first half of i in memory
        write R2 to second half of i in memory
        <end of interrupt. Back to main context>
      write R2 to second half of i in memory
    

    sig_atomic_t

        2
  •  2
  •   Peter G.    15 年前

    int64_t a = 2^32-1;
    
    void some_signal_handler()
    {
       ++a;
    }
    
    void f()
    {
      if( a == 0 )
        printf("a is zero");
    }
    

        3
  •  1
  •   R.. GitHub STOP HELPING ICE    15 年前

    推荐文章