Threads[Mutex]
Create
create a new mutex
Calling Sequence
Description
Examples
Create()
The Create command is used to create a new Mutex. This command returns an integer identifier that is used to represent the mutex.
The Create command does not accept any arguments.
Once created, the mutex can be locked and unlocked using the Lock and Unlock commands.
When a mutex is no longer needed, it should be destroyed using the Destroy command. This will release all the resources used by the mutex.
For more information on using mutexes, see the Mutex help page.
p := proc( m ) global count; print( count ); count := count+1; end proc;
p≔procmglobalcount;print⁡count;count ≔ count+1end proc
count≔1
Create ten threads running the p function.
ThreadsWait⁡seq⁡ThreadsCreate⁡p⁡m,i=1..10
1
2
3
4
5
6
8
10
Without mutexes the same value may be printed multiple times. (You may have to execute this command multiple times to see this occur.)
p := proc( m ) global count; Threads[Mutex][Lock]( m ); print( count ); count := count+1; Threads[Mutex][Unlock]( m ); end proc;
p≔procmglobalcount;Threads[Mutex][Lock]⁡m;print⁡count;count ≔ count+1;Threads[Mutex][Unlock]⁡mend proc
m≔ThreadsMutexCreate⁡
m≔1
Create ten threads running the new p function.
ThreadsWait⁡seq⁡ThreadsCreate⁡p⁡m,i=1..10:
7
9
Using a mutex allows you to control access to the shared variable. Thus each number will be printed only once.
ThreadsMutexDestroy⁡m
See Also
Threads
Threads[Create]
Threads[Mutex][Destroy]
Threads[Mutex][Lock]
Threads[Mutex][Unlock]
Download Help Document