Alice Polansky
Alice Polansky

Reputation: 3241

lock all threads but one in python

i have threads starting point

for _ in xrange(THREADS_COUNT):
        global thread_
        thread_ = threading.Thread(target=self.mainWork, args=(mainProject,victims))
        thread_.start()
        time.sleep(5)

and i need to lock all threads but one(in which happened if) when if occur.

if 'di_unread_inbox' in inbox_page:
    ...

and when else condition occur, i need to unlock threads if them are locked(check for locking required i think)

Upvotes: 0

Views: 1256

Answers (1)

dano
dano

Reputation: 94921

You need to acquire a lock before checking the if condition, and then release it once you've either 1) updated the shared resource, or 2) determined the resource doesn't need updating, and another logic branch should be used. That logic looks like this:

lock = threading.Lock()


def mainWork():
    # do stuff here
    lock.acquire()
    if 'di_unread_inbox' in inbox_page:
        try:
            # something in here changes inbox_page so that 'di_unread_inbox' isn't there anymore
            inboxmessagelabel.set("some label")
        finally:
            lock.release()
    else:
        lock.release()
        # do other stuff

If you don't need the else block, the logic looks a bit simpler:

def mainWork():
    # do stuff here
    with lock:
        if 'di_unread_inbox' in inbox_page:
            inboxmessagelabel.set("some label")

    # do other stuff

Upvotes: 3

Related Questions