How to prevent optimization of busy-wait

后端 未结 1 1967
盖世英雄少女心
盖世英雄少女心 2021-01-22 11:22

I need to have a function busy-wait.

for(long int j=0; j<50000000; ++j)
  ;

When I compile in release mode, this gets optimized out. Other t

相关标签:
1条回答
  • 2021-01-22 12:05

    I don't know why you need to keep the CPU busy, but let's assume that you really have a good reason, like making sure you keep the CPU busy so it doesn't think about that breakup it went through last week and get all depressed but I digress...

    The problem you are seeing is that the compiler performs "dead code elimination": it sees that the loop does nothing (i.e. has no side-effects) and so cuts it out. So you could make it have a side-effect.

    A simple solution would be this function:

    void busywait(long iterations)
    {
        for(volatile long i = 0; i != iterations; i++)
            ;
    }
    

    By marking i as volatile you are ensuring that the loop has side-effects, since stores to volatile objects (i.e. the incrementing we perform) are treated as having side-effects.

    0 讨论(0)
提交回复
热议问题