Python 3.4 - Threading Module

 The threading module allows a program to run multiple operations at the same time in the same process space.

import threading
from queue import Queue
import time

print_lock = threading.Lock()


def exampleJob(worker):
    time.sleep(0.5)

    with print_lock:
        print(threading.current_thread().name, worker)


def threader():
    while True:
        worker = q.get()
        exampleJob(worker)
        q.task_done()


q = Queue()

for x in range(10):
    t = threading.Thread(target=threader)

    t.daemon = True
    t.start()

start = time.time()

for worker in range(20):
    q.put(worker)

q.join()

print('entire job took:', time.time() - start)

/Users/mattfassnacht/PycharmProjects/untitled6/venv/bin/python /Users/mattfassnacht/PycharmProjects/untitled6/functions.py
Thread-1 0
Thread-2 1
Thread-8 7
Thread-6 5
Thread-7 6
Thread-10 9
Thread-4 3
Thread-9 8
Thread-5 4
Thread-3 2
Thread-2 11
Thread-8 12
Thread-10 15
Thread-4 16
Thread-9 17
Thread-7 14
Thread-5 18
Thread-6 13
Thread-1 10
Thread-3 19
entire job took: 1.007871150970459

Process finished with exit code 0

https://www.youtube.com/watch?v=NwH0HvMI4EA

Comments

Popular posts from this blog

Pyhton 3.4 - Continue

Conversations Ongoing: Valuing Modernization in Early European History

Conversations Ongoing: A Bunch of Amateurs