[Python] python: if key not in dictionary add the key. preventing race conditions with...

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    i am programming a telegram bot where more thread handles every update async. i hard code an empty dictionary and while the bot is running, multiple threads write and read from it.

    The most common operation is:

    if key not in dict:
    dict[key] = value
    else:
    dict[key].append(another_value)


    the problem is that while a thread check if key is or not in dict, and maybe it is not, another thread wrote the key in it.

    so basically i have to get rid of this racing condition.

    i need a fast solution. searching on the web i found answers talking about threading.Lock(). Those answers are about 10 years old. i wonder if nowadays it's still a good solution or maybe there is some more new library

    Continue reading...

Compartilhe esta Página