Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sync primitives can I use with clone(2) (C/C++)?

What C++ synchronization primitives can I use when using Linux's clone(2) threads? I specifically cannot use pthreads because I'm building a shared library that replaces many of pthreads's function calls with different definitions, but I'm in need of a mutex of some sort.

EDIT: I might have spoke too soon, I looked at the pthread docs and they use a futex(2) to implement these primitives. I'm assuming that is how I would do this, too?

like image 817
sholsapp Avatar asked Feb 03 '26 04:02

sholsapp


2 Answers

You can use futex http://en.wikipedia.org/wiki/Futex

Here are simple mutex and cond var based on futex http://locklessinc.com/articles/mutex_cv_futex/

like image 94
osgx Avatar answered Feb 05 '26 17:02

osgx


Depending on what your requirements are for your synchronization tool you can also use atomic operations. E.g gcc's __sync_lock_test_and_set can be easily used for a spinlock. Such userspace locks that avoid system calls can in many cases be more efficient than kernel based solutions.

Edit: This is the case if you have just a few instructions to protect. Then the probability that a thread that has taken the spinlock is interrupted while holding the lock is very small. If this happens, the waiting time would then be some scheduling cycles, something that on modern systems should only be a no-go for real-time systems. For the average waiting time this should be negligible.

like image 33
Jens Gustedt Avatar answered Feb 05 '26 18:02

Jens Gustedt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!