Macaulay2 » Documentation
Packages » Macaulay2Doc » The Macaulay2 language » Thing » Mutex » lock » lock(Mutex,Function)
next | previous | forward | backward | up | index | toc

lock(Mutex,Function) -- make a function thread-safe

Description

This function creates a thread-safe version of f. In particular, it takes a mutex and returns a new function that locks it when the function is called and unlocks it when complete, even if there is an error.

If mutex is omitted, then a mutex is created behind the scenes. Therefore, it's only necessary to define mutex before calling lock if you plan on sharing it between multiple functions.

Consider the following example.

i1 : x = 0

o1 = 0
i2 : f = i -> x += 1;
i3 : parallelApply(1..1000, f);
i4 : x

o4 = 387

You likely see that x ended up less than the expected value of 1000. This is an example of a race condition, as multiple threads were trying to modify the global variable x at the same time.

Let's try again using lock.

i5 : x = 0

o5 = 0
i6 : f = lock f;
i7 : parallelApply(1..1000, f);
i8 : x

o8 = 1000

Ways to use this method:


The source of this document is in Macaulay2Doc/doc_mutex.m2:138:0.