Deepika
Deepika

Reputation: 41

How to allow multiple threads to change different parts of an object using locks in Python?

I want to allow different threads to make changes to different elements of Value by acquiring locks only for those elements and not the whole object.

For example: Consider the dictionary -

D = {1:[time, speed, distance],2:[time1,speed1, distance1], 3:[time2, speed2, distance2]}

Thread T1 to modify D[1][0], thread T2 to modify D[1][1], thread T3 to modify D[2][2], etc., Hence T1 should lock D[1][0], T2 should lock D[1][1]. T3 should lock D[2][2] and modify them concurrently.

Upvotes: 2

Views: 305

Answers (1)

Krumelur
Krumelur

Reputation: 32587

In Python, there is the Global Interpreter Lock, so you won't have to worry about locking. You won't get the performance benefit of multithreading either, at least not the way you may be used to from Java or C.

In short, only one thread at a time will run Python code. if you are I/O bound (e.g. Network access), This is the solution you want. If you are CPU bound (e.g. computations), either use native modules or take a look at the multiprocessing module.

Upvotes: 2

Related Questions