Y
Y
Yourmind2021-11-19 20:26:16
Python
Yourmind, 2021-11-19 20:26:16

How to set blocking for only some threads?

I have some code that should be locked only for some threads

name = order.id
lock = Lock()

with lock:
    change_order()


The whole point is that the change_order function should only be locked for threads that have the same order name name = order.id, if the name is different, then the code should not be locked for the thread. So, if a thread with order 1 executes change_order(), then this should in no way interfere with the execution of change_order() by a thread with order 2, but if another thread also has order 1, then change_order() for it should be blocked until the first the thread will not execute it. Is it possible to implement this with lock methods, somehow assigning it to them inside, or will you have to cut your own crutches?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-11-20
@Vindicar

Lock (aka mutex) does not deal with such things.
You can cheat a construction where each order has its own Lock, but this will either be wasteful (if you always create a Lock) or tedious (if you create it when order is accessed).
An asynchronous approach can help, but it will require almost a complete code rewrite. Not very convenient.
In general, it is worth asking a question - is this Lock exactly a bottleneck?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question