Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do libraries implement their own basic locks on windows?

Windows provides a number of objects useful for synchronising threads, such as event (with SetEvent and WaitForSingleObject), mutexes and critical sections.

Personally I have always used them, especially critical sections since I'm pretty certain they incur very little overhead unless already locked. However, looking at a number of libraries, such as boost, people then to go to a lot of trouble to implement their own locks using the interlocked methods on Windows.

I can understand why people would write lock-less queues and such, since thats a specialised case, but is there any reason why people choose to implement their own versions of the basic synchronisation objects?

like image 414
Fire Lancer Avatar asked Nov 29 '22 20:11

Fire Lancer


2 Answers

Libraries aren't implementing their own locks. That is pretty much impossible to do without OS support.

What they are doing is simply wrapping the OS-provided locking mechanisms.

Boost does it for a couple of reasons:

  • They're able to provide a much better designed locking API, taking advantage of C++ features. The Windows API is C only, and not very well-designed C, at that.
  • They are able to offer a degree of portability. the same Boost API can be used if you run your application on a Linux machine or on Mac. Windows' own API is obviously Windows-specific.
  • The Windows-provided mechanisms have a glaring disadvantage: They require you to include windows.h, which you may want to avoid for a large number of reasons, not least its extreme macro abuse polluting the global namespace.
like image 137
jalf Avatar answered Dec 01 '22 09:12

jalf


One particular reason I can think of is portability. Windows locks are just fine on their own but they are not portable to other platforms. A library which wishes to be portable must implement their own lock to guarantee the same semantics across platforms.

like image 35
JaredPar Avatar answered Dec 01 '22 10:12

JaredPar