day40 thread

table of Contents

Thread queue
1
2
3
thread timer
process pools and thread pool
thread queue
1
Import Queue

q=queue.Queue()
q.put('123')
q.put('456')
q.put('789')
print(q.get())
print(q.get())
print(q.get())
q.task_done()

q.task_done()

q.task_done ()
q.join () # Wait until queue elements are consumed before the next step
q.put (1)
Print (q.get ())
2
Import Queue

q = queue.LifoQueue () # stack advanced after
q.put ( '123')
q.put ( '456')
q.put ( '789')
Print (q.get ())
Print (q.get ())
Print (q.get ())
q.task_done ()
q.task_done ()
q.task_done ()
q.join () # wait until queue elements are consumed before the next step
q.put (1)
Print (q.get ())
. 3
Import Queue

q = queue.PriorityQueue () # input in the form of tuples, the first priority for the shaping, the output of the first small
q.put ((. 1, '123'))
q.put ((. 4, '456'))
q.put ((2, '789'))
Print (q.get ())
Print (q.get ())
Print (q.get ())
q.task_done ()
q.task_done ()
q.task_done ( )
q.join () # wait until queue elements are consumed before the next step
q.put ((1, 'AD'))
Print (q.get ())
threaded timer
from the thread threading Import, the timer
Import Time

def test():
print('start')
time.sleep(1)
print('end')

t = Timer (3, function = test) # 3 seconds to open the thread
t.start ()
process pools and thread pools
from concurrent.futures ThreadPoolExecutor Import
Import Time

def test():
print(time.time())
time.sleep(1)
# return i**3
pool=ThreadPoolExecutor(5) #线程池,进程池用ProcessPoolExecutor
list=[]
for i in range(20):
furture=pool.submit(test)
list.append(furture)
for i in list:
print(i.result())
from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor
from threading import currentThread
from multiprocessing import current_process
import time

Task DEF (I):
Print (F '{currentThread () name.}} In the tasks I {')
# Print (F 'process {current_process () name.}} In the tasks I {')
the time.sleep ( . 1)
return I ** 2

the parse DEF (Future):
# processing result to get the
print (future.result ())

IF name == ' main ':
the pool the ThreadPoolExecutor = (. 4) # 4 threads only pool
# pool = ProcessPoolExecutor (4) # 4 threads only pool
fu_list = []
for I in Range (20 is):
# the pool. submit (task, i) # task tasks to be done 20 times, four thread is responsible to do this thing
future = pool.submit (task, i) # task tasks to be done 20 times, four process is responsible to do this thing
future.add_done_callback ( the parse)
# for the current task to bind a function, when the current mandate ends this function will trigger,
# will future object as a parameter to the function
# this callback function is called, come back to deal with the end call this function.

    # print(future.result()) # 如果没有结果一直等待拿到结果,导致了所有的任务都在串行

# pool.shutdown() # 关闭了池的入口,会等待所有的任务执行完,结束阻塞.
# for fu in fu_list:
#     print(fu.result())

Guess you like

Origin www.cnblogs.com/TMesh-python/p/11568081.html