Hi Tady,
First, in the global scope, you create a unique lock for threads accessing your variable:
Code:
#include "TeensyThreads.h"
Threads::Mutex myLock1;
Threads::Mutex myLock2;
The above demonstrates creating 2 locks, you can create as many as you want, and then to use them we do something like this:
Code:
void loop() {
if ( someCondition ) {
[COLOR="#FF0000"]{ Threads::Scope scope(myLock1);[/COLOR]
myVariable = 0x1234;
[COLOR="#FF0000"]}[/COLOR]
}
}
Here we setup a condition as an example, not necessary, the RED highlited area, including brackets, are where the lock is activated. The moment that area is exited, the lock is released automatically. We call that a scope lock, and is the safest mutex lock.
So with the above, we do this example:
Code:
void loop() {
if ( someCondition ) {
[COLOR="#FF0000"]{ Threads::Scope scope(myLock1);[/COLOR]
myVariable = 0x1234;
[COLOR="#FF0000"]}[/COLOR]
}
}
void myThread() {
if ( someCondition ) {
[COLOR="#FF0000"]{ Threads::Scope scope(myLock1);[/COLOR]
myVariable = 0x5678;
[COLOR="#FF0000"]}[/COLOR]
}
}
in the above code, myLock1 is being used in 2 threads. myVariable is encapsulated in the scope lock. Only the first thread to access that scope will automatically lock the variable. To answer your question on what happens when the other thread runs into the lock, it just sits and wait, typically resembling a *while(1);* (wait forever). The moment the locked thread is done, lock is released, and the waiting thread continues on afterwards. This happens vary fast and not noticable by the user.
All your locking must be of "matching" name.
Different locks can lock in any order, but it's important to know NEVER put a lock WITHIN the same scope of another lock!
Ex:
Code:
void loop() {
if ( someCondition ) {
[COLOR="#FF0000"]{ Threads::Scope scope(myLock1);[/COLOR]
[COLOR="#FF0000"]{ Threads::Scope scope(myLock2);[/COLOR]
myVariable = 0x1234;
[COLOR="#FF0000"]}[/COLOR]
[COLOR="#FF0000"]}[/COLOR]
}
}
This may lead to a deadlock if not removed in reverse order or if another thread locks myLock2 and then myLock1, you can also deadlock if the same thread activates the same mutex lock like this:
Code:
void loop() {
if ( someCondition ) {
[COLOR="#FF0000"]{ Threads::Scope scope([COLOR="#FF0000"]myLock1[/COLOR]);[/COLOR]
[COLOR="#FF0000"]{ Threads::Scope scope([COLOR="#FF0000"]myLock1[/COLOR]);[/COLOR]
myVariable = 0x1234;
[COLOR="#FF0000"]}[/COLOR]
[COLOR="#FF0000"]}[/COLOR]
}
}
Your code would appear to be frozen forever. So to keep safe, only lock 1 mutex session per scope, do NOT do recursive locks, and don't lock 2 or more mutexes in the same thread at the same time