All of the tutorials i have seen for Mutex locking with the pThread library have used a Global Mutex Lock:
See:
https://computing.llnl.gov/tutorials/pthreads/#Mutexes
http://www.drdobbs.com/cpp/184401518?pgno=3 (for boost::thread but same context)
What I would like to do is to use Mutex locking where the Global of the main file is out of scope for the function needing to lock the variable. here is an example:
Main.cpp
int main() {
some initilisation code.
tree * tree1;
*Start thread to visualise tree* (see code below)
Mutex Lock:
delete tree1;
tree1 = newTree();
Mutex Unlock
visualiser.cpp
visualise(Tree *) {
Forever:
Mutex Lock:
Check for tree change.
Update tree image.
Display tree image.
Mutex Unlock
I would like to know if this is possible:
- Without global scope mutex locks.
- If possible without passing the mutex to the visualise function.
I understand that this may not be plausable, if not how would i get the global scope variable to the visualiser.cpp, using an extern?
Also if i need to pass the mutex to the function how would i go about doing that?
Yes, provided the mutex stays in scope while any thread is using it, it doesn’t have to be global. You do have to tell the second thread where the mutex is, there’s no way around that unfortunately.
And passing it is no different from passing any other variable.
So, simply define it and initialise it in your first thread then, when creating your second thread, pass its address as the thread argument.
The second thread can then use that address to access the mutex.
In terms of your comment where you want a function to be both usable as a thread and simply a normal function, I’d steer clear of that just because of the complexity.
What you can do is to put most of the work into a normal function and then make the thread function a simple wrapper around that. You can even pass in a mutex pointer which can be used if valid, or not used if NULL.
See the following complete program for details. First, some support stuff, needed headers and a logging function:
Next, the function which will do the work. This is built in such a way that it can be called from any thread, and can be passed a mutex pointer if you want it to use one:
Then an actual thread function, which is really a thin wrapper around the work function above. Note that it receives the mutex via the thread-specific parameter and passes that on to the work function:
And finally, the main function. This first calls the work function without a mutex, then creates a mutex for sharing with the other thread:
You can see in the output how the code sequences itself:
Note especially how the direct call with no mutex acts, as compared to the call with the mutex.