[Python] Should I use mutex in my class or it is redundant because of GIL?

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class with two threads

    1. MainThread - solving tasks one by one(getting self.cur_task_id, and changing self.cur_task_status)
    2. Thread self.report_status_thread - read self.cur_task_id, self.cur_task_status and send values via http

    I am using mutex to synchronize these threads. Should I use mutex in my class or it is redundant because of GIL (Global Interpreter Lock)

    class DeepAllocationService():
    def __init__(self,):
    self.mutex = threading.Lock() # ensure cur_task_id and cur_task_status changed in the same thread
    self.cur_task_id = None
    self.cur_task_status = None
    self.report_status_thread = threading.Thread(target=self.periodic_send_status)

    def periodic_solve_tasks(self,):
    self.report_status_thread.start()

    while True:
    try:
    new_task, task_file = self.get_new_task()
    if new_task:
    self.update_task_info(new_task["id"], new_task["status"])
    self.solve_task(new_task, task_file)
    except Exception as e:
    self.cur_task_status = TaskStatus.ERROR
    self.logger.error(f"Exception in periodic_solve_tasks: {e}")
    finally:
    time.sleep(1)

    def update_task_info(self, task_id=None, task_status=None):
    self.mutex.acquire()
    self.cur_task_id = task_id
    self.cur_task_status = task_status
    self.mutex.release()

    def periodic_send_status(self,):
    while True:
    # read-only function - read and send self.cur_task_id and self.cur_task_status
    time.sleep(2)

    Continue reading...

Compartilhe esta Página