线程
python创建新线程的模块是threading,例子如下:
1. 创建一个类继承theading.Thread
import threading
import time
class MyThread (threading.Thread): #继承父类threading.Thread
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.name = name
def run(self): #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
print ("Starting " + self.name)
time.sleep(1)
print ("Exiting " + self.name)
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启线程
thread1.start()
thread2.start()
print "Exiting Main Thread"
2. 直接利用thread.Thread产生线程
import threading
t=threading.Thread(target=func1,deamo=False,name="BIG",args=("hello"))
t.start() #启动线程
创建进程
python创建新线程的模块是multiprocessing,例子如下:
from multiprocessing import Process
import os
# 子进程要执行的代码
def run_proc(name):
print('Run child process %s (%s)...' % (name, os.getpid()))
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Process(target=run_proc, args=('test',))
print('Child process will start.')
p.start()
p.join()
print('Child process end.')
p.join的作用是p这个进程先执行完,然后调用join的进程再继续执行。
如果想创建进程池,也是实用multiprocessing模块。
from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print('Run task %s (%s)...' % (name, os.getpid()))
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print('Task %s runs %0.2f seconds.' % (name, (end - start)))
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Pool(4)
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
p.close(),在调用close()方法之后,就不能继续向p里面添加新的进程了。
网友评论