Proper use of mutexes in Python

前端 未结 4 2001
北荒
北荒 2020-12-04 07:04

I am starting with multi-threads in python (or at least it is possible that my script creates multiple threads). would this algorithm be the right usage of a Mutex? I haven\

4条回答
  •  盖世英雄少女心
    2020-12-04 07:42

    I would like to improve answer from chris-b a little bit more.

    See below for my code:

    from threading import Thread, Lock
    import threading
    mutex = Lock()
    
    
    def processData(data, thread_safe):
        if thread_safe:
            mutex.acquire()
        try:
            thread_id = threading.get_ident()
            print('\nProcessing data:', data, "ThreadId:", thread_id)
        finally:
            if thread_safe:
                mutex.release()
    
    
    counter = 0
    max_run = 100
    thread_safe = False
    while True:
        some_data = counter        
        t = Thread(target=processData, args=(some_data, thread_safe))
        t.start()
        counter = counter + 1
        if counter >= max_run:
            break
    

    In your first run if you set thread_safe = False in while loop, mutex will not be used, and threads will step over each others in print method as below;

    but, if you set thread_safe = True and run it, you will see all the output comes perfectly fine;

    hope this helps.

提交回复
热议问题