I have an application that at a given intervall loops through a list of items (then length of this list varies) for each item it does a rather simple operation, it’s not just adding a value but neither is it some really complex computations.
What I’m wondering is should i lock for each item like this (current solution):
def method_1:
for item in the_list:
do_operation(item);
def do_operation(item):
lock()
//do some stuff.
unlock()
Or should I do it like this:
def method_1:
lock()
for item in the_list:
do_operation(item);
unlock()
def do_operation(item):
//do some stuff.
I guess this is actually really hard to answer since i assume that much depends on what “do some stuff” is and how long it takes. And I honestly don’t know how much time this takes. Especially compared to how long it takes for python to aquire the lock.
Let me know in the comments if I could improve my question somehow.
I’d suggest locking for the entire list (option 2). If you only lock for each item the list could be modified partway through the operation, which could be problematic depending on what exactly you are doing. There are also overheads associated with each lock and unlock.