PythonBiglove 2019-04-18
综述
多线程是程序设计中的一个重要方面,尤其是在服务器Deamon程序方面。无论何种系统,线程调度的开销都比传统的进程要快得多。
Python可以方便地支持多线程。可以快速创建线程、互斥锁、信号量等等元素,支持线程读写同步互斥。美中不足的是,Python的运行在Python 虚拟机上,创建的多线程可能是虚拟的线程,需要由Python虚拟机来轮询调度,这大大降低了Python多线程的可用性。希望高版本的Python可以 解决这个问题,发挥多CPU的最大效率。
网上有些朋友说要获得真正多CPU的好处,有两种方法:
1.可以创建多个进程而不是线程,进程数和cpu一样多。
2.使用Jython 或 IronPython,可以得到真正的多线程。
闲话少说,下面看看Python如何建立线程
Python线程创建
使用threading模块的 Thread类
类接口如下
代码如下:
class Thread( group=None, target=None, name=None, args=(), kwargs={})代码如下:
def worker(a_tid,a_account): ... th = threading.Thread(target=worker,args=(i,acc) ) ;
启动这个线程
代码如下:
th.start()
代码如下:
threading.Thread.join(th)
代码如下:
g_mutex = threading.Lock() ....
代码如下:
for ... : #锁定,从下一句代码到释放前互斥访问 g_mutex.acquire() a_account.deposite(1) #释放 g_mutex.release()
import time,datetime
import threading
def worker(a_tid,a_account):
global g_mutex
print("Str " , a_tid, datetime.datetime.now() )
for i in range(1000000):
#g_mutex.acquire()
a_account.deposite(1)
#g_mutex.release()
print("End " , a_tid , datetime.datetime.now() )
class Account:
def __init__ (self, a_base ):
self.m_amount=a_base
def deposite(self,a_amount):
self.m_amount+=a_amount
def withdraw(self,a_amount):
self.m_amount-=a_amount
if __name__ == "__main__":
global g_mutex
count = 0
dstart = datetime.datetime.now()
print("Main Thread Start At: ", dstart)
#init thread_pool
thread_pool = []
#init mutex
g_mutex = threading.Lock()
# init thread items
acc = Account(100)
for i in range(10):
th = threading.Thread(target=worker,args=(i,acc) ) ;
thread_pool.append(th)
# start threads one by one
for i in range(10):
thread_pool[i].start()
#collect all threads
for i in range(10):
threading.Thread.join(thread_pool[i])
dend = datetime.datetime.now()
print("count=", acc.m_amount)
print("Main Thread End at: ", dend, " time span ", dend-dstart)注意,先不用互斥锁进行临界段访问控制,运行结果如下:
从结果看到,程序确实是多线程运行的。但是由于没有对对象Account进行互斥访问,所以结果是错误的,只有3434612,比原预计少了很多。
打开锁后:
这次可以看到,结果正确了。运行时间比不进行互斥多了很多,不过这也是同步的代价。
同时发现,写多线程,多进程类的程序,不能用自带的idle来运行。会有错误。