concurrent.futures
提供ThreadPoolExecutor(线程池)和ProcessPoolExecutor(进程池)
from concurrent. futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, as_completed
from concurrent. futures import ProcessPoolExecutor
import time
def test ( n) :
for i in range ( n) :
print ( i)
time. sleep( 1 )
return n
with ThreadPoolExecutor( max_workers= 5 ) as t:
task1 = t. submit( test, 4 )
task2 = t. submit( test, 3 )
print ( task1. done( ) )
time. sleep( 5 )
print ( task2. result( ) )
00
False
1
1
2
2
3
3
with ThreadPoolExecutor( max_workers= 5 ) as t:
all_task = [ t. submit( test, i) for i in range ( 5 ) ]
wait( all_task, return_when= FIRST_COMPLETED)
print ( '4' )
0
0
0
0
4
11
1
22
3
with ThreadPoolExecutor( max_workers= 5 ) as t:
all_task = [ t. submit( test, i) for i in range ( 5 ) ]
for task in as_completed( all_task) :
data = task. result( )
00
0
0
11
1
22
3
executor = ThreadPoolExecutor( max_workers= 5 )
result = executor. map ( test, [ 4 , ] )
print ( 'asd' )
executor. shutdown( )
0
asd
Object `executor.shutdown()` not found.
1
2
3
from concurrent. futures import ProcessPoolExecutor
threading 线程
import threading
import time
def test ( ) :
time. sleep( 3 )
print ( 'done' )
a = threading. Thread( target= test)
a. start( )
a. is_alive( )
a. join( timeout= 1 )
a. is_alive( )
True
done
class TestThread ( threading. Thread) :
def __init__ ( self, name= None ) :
threading. Thread. __init__( self, name= name)
def run ( self) :
for i in range ( 5 ) :
print ( threading. current_thread( ) . name, i)
time. sleep( 1 )
thread = TestThread( name= 'test' )
thread. start( )
test 0
test 1
test 2
test 3
test 4
lock = threading. lock( )
lock. acquire( )
lock. release( )