Mutex
When multiple threads simultaneously access and modify shared data, data races can occur, leading to unpredictable results. Mutex solves this problem by ensuring that only one thread can enter a critical section at a time.
Cangjie uses the Mutex type as a reentrant mutex. Reentrant means that the same thread can acquire the same lock multiple times without causing a deadlock. Basic operations on Mutex include lock() to acquire the lock and unlock() to release the lock.
To simplify lock management, Cangjie provides the synchronized keyword. synchronized(mtx) automatically acquires the lock when entering a code block and releases it when exiting, ensuring proper release even if an exception occurs or an early return happens.
The code on the right creates 20 threads, each performing an increment operation on the shared variable count. Using synchronized(mtx) protects the critical section, ensuring the final result is correct.
synchronized automatically releases the lock without requiring a manual unlock() call, which is safer than explicit lock()/unlock().Try removing the synchronized block and run the program multiple times to observe whether the results are consistent.