python thread pool code example
Example 1: threading python
import threading
import time
def thread_function(name):
print(f"Thread {name}: starting")
time.sleep(2)
print(f"Thread {name}: finishing")
my_thread = threading.Thread(target=thread_function, args=(1,))
my_thread.start()
time.sleep(1)
my_second_thread = threading.Thread(target=thread_function, args=(2,))
my_second_thread.start()
my_second_thread.join()
Example 2: how to thread python
import threading, time
def worker():
"""thread worker function"""
print('Worker')
return
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
print('Thread')
Example 3: python threading
def myFunction(x, y):
pass
x = threading.Thread(target=myFunction, args=(x, y))
x.start()
Example 4: worker pool model with multiprocessing
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
Example 5: python threading queue
import threading, queue
q = queue.Queue()
def worker():
while True:
item = q.get()
print(f'Working on {item}')
print(f'Finished {item}')
q.task_done()
threading.Thread(target=worker, daemon=True).start()
for item in range(30):
q.put(item)
print('All task requests sent\n', end='')
q.join()
print('All work completed')
Example 6: python thread pool
from multiprocessing import Pool
def test( v ):
print(v)
return v
if __name__ == '__main__':
with Pool(2) as p:
print(p.map(test, range(5)))