线程的概念
线程是CPU调度的基本单元,线程运行于进程当中,一个进程中可以运行很多个线程。同一进程中的所有线程共享内存空间
threading
Thread # 表示一个线程的执行的对象
start() # 开始线程的执行
run() # 定义线程的功能的函数(一般会被子类重写)
join(timeout=None) # 允许主线程等待线程结束,程序挂起,直到线程结束;如果给了timeout,则最多等待timeout秒.
getName() # 返回线程的名字
setName(name) # 设置线程的名字
isAlive() # 布尔标志,表示这个线程是否还在运行中
isDaemon() # 返回线程的daemon标志
setDaemon(daemonic) # 后台线程,把线程的daemon标志设置为daemonic(一定要在调用start()函数前调用)
# 默认主线程在退出时会等待所有子线程的结束。如果希望主线程不等待子线程,而是在退出时自动结束所有的子线程,就需要设置子线程为后台线程(daemon)
Lock # 锁原语对象
Rlock # 可重入锁对象.使单线程可以在此获得已获得了的锁(递归锁定)
Condition # 条件变量对象能让一个线程停下来,等待其他线程满足了某个条件.如状态改变或值的改变
Event # 通用的条件变量.多个线程可以等待某个事件的发生,在事件发生后,所有的线程都会被激活
Semaphore # 为等待锁的线程提供一个类似等候室的结构
BoundedSemaphore # 与Semaphore类似,只是不允许超过初始值
Time # 与Thread相似,只是他要等待一段时间后才开始运行
activeCount() # 当前活动的线程对象的数量
currentThread() # 返回当前线程对象
enumerate() # 返回当前活动线程的列表
settrace(func) # 为所有线程设置一个跟踪函数
setprofile(func) # 为所有线程设置一个profile函数
python中多线程
import os
import time
from random import randint
from threading import Thread
def download(name):
print("name:{} download task pid :{}, parent pid:P{}".format(name, os.getpid(), os.getppid()))
download_time = randint(5, 10)
time.sleep(download_time)
print("download task finished cost_time:{}".format(download_time))
if __name__ == '__main__':
start = time.time()
print("current python_thread pid is:%d" % os.getpid())
thread_list = []
for i in range(10):
t = Thread(target=download, args=(i,))
t.start()
# t.run()
thread_list.append(t)
for j in thread_list:
j.join()
end = time.time()
print("total cost_time:%.3f" % (end - start))
自定义线程
import time
from random import randint
from threading import Thread
class MyThread(Thread):
def __init__(self, name):
super(MyThread, self).__init__()
self._filename = name
def run(self):
print("MyThread start run %s" % self._filename)
download_time = randint(5, 10)
time.sleep(download_time)
print("%s download finished time:%d" % (self._filename, download_time))
if __name__ == '__main__':
start = time.time()
thread_list = []
for i in range(10):
t = MyThread(str(i))
t.start()
thread_list.append(t)
for j in thread_list:
j.join()
end = time.time()
print("total cost time %.3f" % (end - start))
线程锁机制
from time import sleep
from threading import Thread, Lock
class Account(object):
def __init__(self):
self._balance = 0
self._lock = Lock()
def deposit(self, money):
self._lock.acquire()
try:
# 计算存款后的余额
new_balance = self._balance + money
# 模拟受理存款业务需要0.01秒的时间
sleep(0.01)
# 修改账户余额
self._balance = new_balance
finally:
self._lock.release()
@property
def balance(self):
return self._balance
class AddMoneyThread(Thread):
def __init__(self, account, money):
super().__init__()
self._account = account
self._money = money
def run(self):
self._account.deposit(self._money)
def main():
account = Account()
threads = []
# 创建100个存款的线程向同一个账户中存钱
for _ in range(100):
t = AddMoneyThread(account, 1)
t.start()
threads.append(t)
# 等所有存款的线程都执行完毕
for t in threads:
t.join()
print('账户余额为: ¥%d元' % account.balance)
if __name__ == '__main__':
main()