2

Простой скрипт:

import threading
import time
total = 0
lock = threading.Lock()
def update_total(amount):
    global total, lock
    time.sleep(2)
    lock.acquire()
    time.sleep(0.2)
    total += amount
    print(total)
    lock.release()

if __name__ == '__main__':
    for i in range(10):
        my_thread = threading.Thread(target=update_total, args=(5,))
        my_thread.start()

2 вопроса:

1) Как отследить время выполнения всех потоков? Если я в потоках буду забивать какие то переменные start и finish, то мне нужно их вывести в основном потоке после выполнения всех потоков.

2) Как вывести total после обработки всеми потоками в основном потоке?

1 ответ 1

2

Нашел решение:

import threading
import time
total = 0
lock = threading.Lock()
def update_total(amount):
    global total, lock
    time.sleep(2)
    lock.acquire()
    time.sleep(0.2)
    total += amount
    print(total)
    lock.release()

threads=[]
if __name__ == '__main__':
    start = time.time()
    for i in range(10):
        my_thread = threading.Thread(target=update_total, args=(5,))
        my_thread.start()
        threads.append(my_thread)
    for thread in threads:
        thread.join()
    print("Total:"+str(total))
    print("runtime: {:0.2f}".format(time.time()-start))

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.