Can Mutex be replaced with anything?

Hi All,

To avoid race condition, instead of using mutex, semaphore, spinlock etc.... Is there any other mechanism by which we can avoid race condition in an multi-threading environment.

-Thanks

Try to search something about interlocked variables.

Thanks, kandrewo.

Interlocked variables/operations are mostly a Microsoft win32 thing. Because some architectures capable of running Linux do not have the necessary hardware support, interlocked variables/operations are not available in Linux user space. They are available only in the kernel and only on some architectures.

Mutexes, semaphores, and atomic operations have been around for decades, have been used by untold numbers of programmers, and have been examined, re-examined, and otherwise worked on by probably thousands of computer scientists and programmers of which probably more than a few have done Nobel-prize level work in science and/or mathematics.

They're mature, stable, and work without fail.

They're also just about as fast as possible.

If you think you can do better, go ahead. You may very well come up with something that's better. But be sure when you're done developing your alternative, you compare the performance you get to the OS-supplied mutexes, semaphores and atomic operations, because coming up with something better is going to be very hard to do.

But if you can do it, it would be great.

If I'm reading it right, an interlocked variable looks a lot like a linux futex, the atomic part of which does happen in userspace.

You are right. But there are some interesting differences.

A futex (fast userspace mutex) is essentially a userspace 32-bit or 64-bit address (lock) located in a shared memory region together with a matching kernel wait queue (futex queue). In the noncontended case, a lock can be acquired/released from userspace without having to enter the kernel. In the contended case, the kernel gets involved.

Implementation-wise, futexes are closer to slim reader/writer (SRW) locks than to interlocked variables.

Yes. For instance on SMP machine, you can use so-called "lock free algorithms". There are no standard library for those algorithms yet, and they are highly HW dependent. So unless you have an absolute need for performance, I would recommend against it and stick to classical synchronization devices like mutex, spinlock etc.

Cheers,
Lo�c.