How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

后端 未结 10 725
攒了一身酷
攒了一身酷 2020-11-22 12:58

I\'ve been digging through some parts of the Linux kernel, and found calls like this:

if (unlikely(fd < 0))
{
    /* Do something */
}

o

10条回答
  •  悲哀的现实
    2020-11-22 13:20

    As per the comment by Cody, this has nothing to do with Linux, but is a hint to the compiler. What happens will depend on the architecture and compiler version.

    This particular feature in Linux is somewhat mis-used in drivers. As osgx points out in semantics of hot attribute, any hot or cold function called with in a block can automatically hint that the condition is likely or not. For instance, dump_stack() is marked cold so this is redundant,

     if(unlikely(err)) {
         printk("Driver error found. %d\n", err);
         dump_stack();
     }
    

    Future versions of gcc may selectively inline a function based on these hints. There have also been suggestions that it is not boolean, but a score as in most likely, etc. Generally, it should be preferred to use some alternate mechanism like cold. There is no reason to use it in any place but hot paths. What a compiler will do on one architecture can be completely different on another.

提交回复
热议问题