Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex in C++ BEFORE C++11

Tags:

c++

mutex

c++03

Question is simple - what are simple, ready-to-use solutions for mutexes in C++ before C++11 ? I need nothing fancy - just some bit of code to wait for another callback (that may happen anytime) to finish before executing.

I'm running on your everyday PC, i7 and whatnot. No specific performance requirements (simply not too slow), but must do the job of stopping one process and let the other finish and then resume the first one.

Thanks in advance !

like image 449
Charles Avatar asked Jan 26 '17 10:01

Charles


People also ask

What is a mutex in C?

(since C++11) The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

When would you use a mutex lock?

Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time.

Is mutex preemptive?

The process in spinlock may not sleep while waiting for the lock. In contrast, the process in mutex may sleep while waiting for the lock. Spinlock disables preemption. On the other hand, mutex supports preemption.

What is the difference between semaphore and mutex?

A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.


1 Answers

Boost Synchronization is surely a valid option.

If you don't want to use Boost (based on your question you may find it overkill for your needs), you can write your own c++ class wrapper around the API provided by your target platform (i.e. POSIX thread mutex for POSIX compliant platforms, or Windows Mutexes or Critical Sections on Microsoft Windows OS).

There are surely a lot of such wrapper class already implemented by someone else, i.e. you can try searching on GitHub using the mutex keyword and restricting results for code and C++ language (here are a lot of results).

like image 57
roalz Avatar answered Oct 03 '22 16:10

roalz