stdmutex

Why do functions using std::mutex make a null check of the address of pthread_key_create?

∥☆過路亽.° 提交于 2019-11-29 10:06:14
Take this simple function that increments an integer under a lock implemented by std::mutex : #include <mutex> std::mutex m; void inc(int& i) { std::unique_lock<std::mutex> lock(m); i++; } I would expect this (after inlining) to compile in a straightforward way to a call of m.lock() an increment of i and then m.unlock() . Checking the generated assembly for recent versions of gcc and clang , however, we see an extra complication. Taking the gcc version first: inc(int&): mov eax, OFFSET FLAT:__gthrw___pthread_key_create(unsigned int*, void (*)(void*)) test rax, rax je .L2 push rbx mov rbx, rdi

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

北城以北 提交于 2019-11-27 05:46:27
I have two use cases. A. I want to synchronise access by two threads to a queue. B. I want to synchronise access by two threads to a queue and use a condition variable because one of the threads will wait on content to be stored into the queue by the other thread. For use case A I see code example using std::lock_guard<> . For use case B I see code example using std::unique_lock<> . What is the difference between the two and which one should I use in which use case? The difference is that you can lock and unlock a std::unique_lock . std::lock_guard will be locked only once on construction and