目录
进程与线程
1.线程是程序执行的最小单位,而进程是操作系统分配资源的最小单位;
2.一个进程由一个或多个线程组成,线程是一个进程中代码的不同执行路线
3,进程之间相互独立,但同一进程下的各个线程之间共享程序的内存空间(包括代码段,数据集,堆等)及一些进程级的资源(如打开文件和信号等),某进程内的线程在其他进程不可见;
4.调度和切换:线程上下文切换比进程上下文切换要快得多
创建多线程
1. 使用Threading模块创建线程,直接从threading.Thread继承
import time
import threading
def test(x):
print(x)
time.sleep(2)
t1=threading.Thread(target=test,args=(1,))
t2=threading.Thread(target=test,args=(2,))
#target=目标(执行内容),args=接收参数(元组)
t1.start()
t2.start()
除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:
- run(): 用以表示线程活动的方法。
- start():启动线程活动。
- join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
- isAlive(): 返回线程是否活动的。
- getName(): 返回线程名。
- setName(): 设置线程名
(摘自菜鸟教程)
2. 创建类
import threading
import time
class MyThread(threading.Thread): # 定义一个类,并继承父类threading.Thread
def __init__(self, n):
super(MyThread, self).__init__()
self.n = n
def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
print("one", self.n)
time.sleep(2)
# 实例化对象
r1 = MyThread(11)
r2 = MyThread(22)
# 启动线程
r1.start()
r2.start()
join()
如果thread是某个子线程,则调用thread.join()的作用是确保thread子线程执行完毕后才能执行下一个线程。下面第一个例子中没有调用join()函数,故没有这个限制,所有线程执行顺序都不定。官方解释是直至启动的线程终止之前一直挂起,除非给出了 timeout(秒) ,否则会一直阻塞,即除非子线程也全部运行完毕,否则主线程一直挂起
线程同步
锁机制
threading的Lock类,用该类的acquire函数进行加锁,用realease函数进行解锁
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting " + self.name)
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
threadLock.acquire()
print_time(self.name, self.counter, 5)
# 释放锁
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
t.join()
print("Exiting Main Thread")
作业
要求:在一个线程中,每秒循环输出当前的年月日时分秒;于此同时,在另一个线程中,实现张三的姓每2秒打印输出4次结束。注意:都需要使用类和继承实现功能
import threading
import time
class myThread(threading.Thread): # 继承父类threading.Thread
def __init__(self, function):
threading.Thread.__init__(self)
self.function= function
def run(self):
if self.function == 1:
self.print_time()
else:
for i in range(4):
print("姓名:张三")
time.sleep(2)
def print_time(threadName):
while True:
time.sleep(1)
print(time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(time.time())))
# 创建新线程
t1=myThread(1)
t2=myThread(2)
# 开启线程
t1.start()
t2.start()