2

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.

Aaron
  • 2,383
  • 3
  • 22
  • 53
Deepika
  • 41
  • 7

1 Answers1

2

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.

Community
  • 1
  • 1
Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • Due to GIL, multiple threads aren't allowed to execute same part of the code. My question is about threads executing different parts of the code but sharing an mutable object. Or did I understand GIL wrongly? – Deepika Mar 03 '15 at 07:50
  • The GIL ensures an *interpreter* runs serialized. At least in CPython, an interpreter is the same as a process. If the object is shared with native code, you would have to take the GIL before modifying it though. – Krumelur Mar 03 '15 at 18:18