Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an inline function atomic?

Can linux context switch after unlock in the below code if so we have a problem if two threads call this

inline bool CMyAutoLock::Lock(
    pthread_mutex_t *pLock,
    bool bBlockOk 
)
throw ()
{
    Unlock();
    if (pLock == NULL)
        return (false);
// **** can context switch happen here ? ****///
    return ((((bBlockOk)? pthread_mutex_lock(pLock) :
        pthread_mutex_trylock(pLock)) == 0)? (m_pLock = pLock, true) : false);
}
like image 347
resultsway Avatar asked Jul 21 '26 22:07

resultsway


1 Answers

No, it's not atomic.

In fact, it may be especially likely for a context switch to occur after you've unlocked a mutex, because the OS knows if another thread is blocked on that mutex. (On the other hand, the OS doesn't even know whether you're executing an inline function.)

like image 77
Dan Breslau Avatar answered Jul 23 '26 15:07

Dan Breslau