What to avoid for performance reasons in multithreaded code?

后端 未结 12 2442
执笔经年
执笔经年 2021-02-09 10:45

I\'m currently reviewing/refactoring a multithreaded application which is supposed to be multithreaded in order to be able to use all the available cores and theoretically deliv

12条回答
  •  孤街浪徒
    2021-02-09 11:14

    Something to keep in mind when locking: lock for as short a time as possible. For example, instead of this:

    lock(syncObject)
    {
        bool value = askSomeSharedResourceForSomeValue();
        if (value)
            DoSomethingIfTrue();
        else
            DoSomtehingIfFalse();
    }
    

    Do this (if possible):

    bool value = false;  
    
    lock(syncObject)
    {
        value = askSomeSharedResourceForSomeValue();
    }  
    
    if (value)
       DoSomethingIfTrue();
    else
       DoSomtehingIfFalse();
    

    Of course, this example only works if DoSomethingIfTrue() and DoSomethingIfFalse() don't require synchronization, but it illustrates this point: locking for as short a time as possible, while maybe not always improving your performance, will improve the safety of your code in that it reduces surface area for synchronization problems.

    And in certain cases, it will improve performance. Staying locked for long lengths of time means that other threads waiting for access to some resource are going to be waiting longer.

提交回复
热议问题