Module Semaphore
Contents
Instructions: Use this module in your project
In the IDE (CLion, Visual Studio Code, Xcode, etc.) you use for your DkSDK project:
Add the following to your project's
dependencies/CMakeLists.txt
:DkSDKProject_DeclareAvailable(ocaml CONSTRAINT "= 4.14.0" FINDLIBS str unix runtime_events threads dynlink) DkSDKProject_MakeAvailable(ocaml)
Add the
Findlib::ocaml
library to any desired targets insrc/*/CMakeLists.txt
:target_link_libraries(YourPackage_YourLibraryName # ... existing libraries, if any ... Findlib::ocaml)
Click your IDE's
Build
button
Not using DkSDK?
FIRST, do one or all of the following:
Run:
opam install ocaml.4.14.0
Edit your
dune-project
and add:(package (name YourExistingPackage) (depends ; ... existing dependenices ... (ocaml (>= 4.14.0))))
Then run:
dune build *.opam # if this fails, run: dune build
Edit your
<package>.opam
file and add:depends: [ # ... existing dependencies ... "ocaml" {>= "4.14.0"} ]
Then run:
opam install . --deps-only
FINALLY, add the unix threads
library to any desired (library)
and/or (executable)
targets in your **/dune
files:
(library
(name YourLibrary)
; ... existing library options ...
(libraries
; ... existing libraries ...
unix threads))
(executable
(name YourExecutable)
; ... existing executable options ...
(libraries
; ... existing libraries ...
unix threads))
Counting semaphores
A counting semaphore is a counter that can be accessed concurrently by several threads. The typical use is to synchronize producers and consumers of a resource by counting how many units of the resource are available.
The two basic operations on semaphores are:
-
"release" (also called "V", "post", "up", and "signal"), which increments the value of the counter. This corresponds to producing one more unit of the shared resource and making it available to others.
-
"acquire" (also called "P", "wait", "down", and "pend"), which waits until the counter is greater than zero and decrements it. This corresponds to consuming one unit of the shared resource.
-
since 4.12
module
Counting
:
sig
...
end
Binary semaphores
Binary semaphores are a variant of counting semaphores where semaphores can only take two values, 0 and 1.
A binary semaphore can be used to control access to a single shared resource, with value 1 meaning "resource is available" and value 0 meaning "resource is unavailable".
The "release" operation of a binary semaphore sets its value to 1, and "acquire" waits until the value is 1 and sets it to 0.
A binary semaphore can be used instead of a mutex (see module
Mutex
) when the mutex discipline (of unlocking the mutex
from the thread that locked it) is too restrictive. The "acquire"
operation corresponds to locking the mutex, and the "release" operation
to unlocking it, but "release" can be performed in a thread different
than the one that performed the "acquire". Likewise, it is safe to
release a binary semaphore that is already available.
- since 4.12
module
Binary
:
sig
...
end