python threading 模块使用多线程。感谢小马哥指点迷津。
#!/usr/bin/env python # -*- coding: UTF-8 -*- import threading threads = [] # 先创建线程对象 for li in db_con: t = threading.Thread(target=update_thread,args=(list,file,db_con,li)) threads.append(t) # 启动所有线程 for i in (0,len(threads)): threads[i].start() #阻塞主线程,直到所有线程完成或超时后执行主线程。参数说明中有解释。 for i in (0,len(threads)): threads[i].join() def update_thread(list,file,db_con,li): ## do something
参数说明:
def __init__(self, group=None, target=None, name=None, args=(), kwargs={})
- 参数group是预留的,用于将来扩展;
- 参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行;
- 参数name是线程的名字。默认值为“Thread-N“,N是一个数字。
- 参数args和kwargs分别表示调用target时的参数列表和关键字参数。
Thread.join([timeout])
- 调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束
例:
#!/usr/bin/env python # -*- coding: UTF-8 -*- import threading, time def doWaiting(): print ‘start waiting:‘, time.strftime(‘%H:%M:%S‘) time.sleep(3) print ‘stop waiting‘, time.strftime(‘%H:%M:%S‘) thread1 = threading.Thread(target = doWaiting) thread1.start() time.sleep(1) #确保线程thread1已经启动 print ‘start join‘ thread1.join() #将一直堵塞,直到thread1运行结束。 print ‘end join‘
网上找到一个经典案例。
链接地址:http://www.jb51.net/article/53918.htm
#-*- encoding: gb2312 -*- import threading import time class Test(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self._run_num = num def run(self): global count, mutex threadname = threading.currentThread().getName() for x in xrange(0, int(self._run_num)): mutex.acquire() count = count + 1 mutex.release() print threadname, x, count time.sleep(1) if __name__ == ‘__main__‘: global count, mutex threads = [] num = 4 count = 1 # 创建锁 mutex = threading.Lock() # 创建线程对象 for x in xrange(0, num): threads.append(Test(10)) # 启动线程 for t in threads: t.start() # 等待子线程结束 for t in threads: t.join()
时间: 2024-11-05 17:27:57