MohammadRB MohammadRB - 1 year ago 65
C++ Question

What happens if i call wait on a notified condition variable

Suppose i have two thread and one shared c++ 11 condition variable.
what happen if thread1 call notify and after that thread2 call wait?
will thread2 block forever or it will continue it's work due to call of notify by thread1?


enum bcLockOperation
bcLockOperation_Light = -1,
bcLockOperation_Medium = 50,
bcLockOperation_Heavy = 1
class BC_COREDLL_EXP bcCustomMutex
bcCustomMutex(const bcCustomMutex&);
bcCustomMutex& operator=(const bcCustomMutex&);

bcAtomic<int> mFlag;
bcMutex mMutex;
bcConditionVariable mCond;

bcCustomMutex() { bcAtomicOperation::bcAtomicInit(mFlag, 0); };
~bcCustomMutex() {};

/*bcMutex(const bcMutex& pOther) = delete;
bcMutex& operator=(const bcMutex& pOther) = delete;*/

bcInline void lock(bcLockOperation pLockOperation = bcLockOperation_Medium)
bcINT32 lNewLoopCount = static_cast<bcINT32>(pLockOperation);
bcINT32 lLoopCounter = 0;
bcINT32 lExpected = 0;
bcINT32 lLoopCount = bcAtomicOperation::bcAtomicLoad(mFlag, bcMemoryOrder_Relaxed);

while (true)
while(bcAtomicOperation::bcAtomicLoad(mFlag, bcMemoryOrder_Relaxed) != 0 &&
lLoopCounter != lLoopCount)
if(lExpected == 0)
else if(lLoopCounter == lLoopCount)
bcLockGuard<bcMutex> lGuard(mMutex);

bcInline void UnLock()
bcAtomicOperation::bcAtomicStore(mFlag, 0, bcMemoryOrder_Relaxed);
bcUniqueLock<bcMutex> lGuard(mMutex);
bcInline bcBOOL TryLock()

I want to write a custom mutex such that each thread can provide an argument that represents the complexity of operations that the current thread wants to execute.
If the complexity of the operation is low other threads will be in a loop like a spin lock but if the complexity of the operation is medium each thread will iterate 50 times and then will sleep by condition variable and if operation is very complex other threads will go to sleep directly.

now assume thread1 locks this mutex and thread2 goes for waiting due to its loopCounter reaching its end and right before locking the condition variable's mutex, thread1 calls notify on the condition variable. Now thread2 will sleep until another thread locks the custom mutex and then calls unlock on it.

I am new to multithreading and i want to learn. I know that my class may contain errors or may be completely wrong, but is there any way to correct this problem or a good algorithm to write such a mutex.

Another question: Are my atomic operation ordering correctly?

Answer Source

Thread2 will block until someone calls notify. Calls to notify release threads that are waiting at the time of the call. If there are no threads waiting, they do nothing. They aren't saved.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download