Call a function before function exits

前端 未结 5 878
抹茶落季
抹茶落季 2021-01-28 21:49

I will begin with an example. Suppose I need to guard a code with a function inside a mutex. There are two ways of implementing this.

#include 
#         


        
5条回答
  •  情书的邮戳
    2021-01-28 22:17

    Here's an example using Boost.ScopeExit (untested):

    #include 
    
    ...
    
    void threadfunc_autolock(int i, float value)
    {
        pthread_mutex_lock(&myMutex);
    
        BOOST_SCOPE_EXIT(&myMutex) {
            pthread_mutex_unlock(&myMutex);
        } BOOST_SCOPE_EXIT_END
    
        if(i <= 0 || i > myVec.size())
        {
            return;
        }
    
        if(value < 0)
        {
            return;
        }
    
        myVec[i] += value;
    }
    

提交回复
热议问题