Do I have to lock all functions that calls to one or more locked function for multi-threading?
Ok I have been reading this article about lock vital statements in the correct way in python.
The example is
lock = threading.Lock() def get_first_part(): lock.acquire() try: ... fetch data for first part from shared object finally: lock.release() return data def get_second_part(): lock.acquire() try: ... fetch data for second part from shared object finally: lock.release() return data def get_both_parts(): lock.acquire() try: first = get_first_part() second = get_second_part() finally: lock.release() # The finally block will alway execute no mater what before this, not matter return/break/continue. https://docs.python.org/2/tutorial/errors.html return first, second
So here is my problem， I have got a serial device control class, that every function in it calls to the vital statements (functions require a thread lock (RLock)).
Some of the functions call to the get_first_part() only, some of them calls both, some of them are more complex and might call like first, second, third, first etc.
So my problem is do I have to put the lock.aquire() and release in every this kind of function in the class ? What's the preferred way to lock and relase all of these functions ? Use the decorators ?
The with statement is way better:
lock = threading.RLock() def get_first_part(): with lock: return ...data for first part...
And yes, of course, you can use a decorator if you wish:
import functools def withlock(func): @functools.wrap(func) def wrapper(*a, **k): with lock: return func(*a, **k) return wrapper
@withlock def get_first_part(): return ...data for first part...
However, it's unusual that the whole body of all functions need to be holding the lock throughout, and the with statement gives you better granularity about what parts exactly need that lock (any preparation and post-processing can happen before acquiring, and after releasing, the lock). So I normally go with the elegant with instead, rather than going for the "gross grained" approach of a decorator in such cases.