sasha sami
sasha sami

Reputation: 525

When to put locks for multi-threading and multi-processing?

Do I need to do this while printing to standard output:

   `lock.acquire()`
    #printing to standard output
    lock.release()

For multi-threads and multi-processes.
Also does this has to be done while just reading from global file or value of a global variable??

PS: I am doing multi- threading and multi-processing in python 2.7.

Upvotes: 0

Views: 305

Answers (2)

Lie Ryan
Lie Ryan

Reputation: 64847

Python's print is thread safe due to GIL, you won't cause wreak to Python's internal state by printing from multiple threads.

However, if you want to make sure that multiple print statements will have all their prints grouped in logical manner, you do need a way to ensure that things are printed in the correct order. One way as you have discovered is to use lock, another IMO easier way is to build a single string that contains everything that needs to be printed together.

Upvotes: 0

JBernardo
JBernardo

Reputation: 33397

you can simplify to

with lock:
    print(something)

But yes, you need to avoid prints to be mixed by various threads.

When using readonly variables, you do not need a lock. When reading files (because you're changing state), you do need.

Upvotes: 1

Related Questions