Python多线程---threading

xiaoxiao2021-02-27  155

1、创建    python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用    1.直接实例        import threading #导入包        t = threading.Thread(target=saySorry) #创建线程,设置目标函数        t.start() #启动线程,即让线程开始执行

       例:

#coding=utf-8 import threading import time def saySorry(): print("亲爱的,我错了,我能吃饭了吗?") time.sleep(1) if __name__ == "__main__": for i in range(5): t = threading.Thread(target=saySorry) t.start() #启动线程,即让线程开始执行 结果:

 

  2.继承threading.Thread

#coding=utf-8 import threading import time class MyThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字 print(msg) if __name__ == '__main__': t = MyThread() t.start() 结果: 

   2、查看线程数量    threading.enumerate():显示当前进程所有正在运行的线程    len(threading.enumerate()): 线程数    threading.current_thread():显示当前运行的线程    In [7]: threading.enumerate()    Out[7]:    [<_MainThread(MainThread, started 140487919113984)>,     <HistorySavingThread(IPythonHistorySavingThread, started 140487852594944)>]         In [9]: threading.current_thread()

   Out[9]: <_MainThread(MainThread, started 140487919113984)>

3、多线程-共享全局变量 例:

from threading import Thread import time def work1(nums): nums.append(44) print("----in work1---",nums) def work2(nums): #延时一会,保证t1线程中的事情做完 time.sleep(1) print("----in work2---",nums) g_nums = [11,22,33] t1 = Thread(target=work1, args=(g_nums,)) t1.start() t2 = Thread(target=work2, args=(g_nums,)) t2.start()

运行结果:

----in work1--- [11, 22, 33, 44] ----in work2--- [11, 22, 33, 44]

总结:

在一个进程内的所有线程共享全局变量,能够在不适用其他方式的前提下完成多线程之间的数据共享(这点要比多进程要好)缺点就是,线程是对全局变量随意遂改可能造成多线程之间对全局变量的混乱(即线程非安全)

4、多线程-非共享数据

例:

#coding=utf-8 import threading import time class MyThread(threading.Thread): # 重写 构造方法 def __init__(self,num,sleepTime): threading.Thread.__init__(self) self.num = num self.sleepTime = sleepTime def run(self): self.num += 1 time.sleep(self.sleepTime) print('线程(%s),num=%d'%(self.name, self.num)) if __name__ == '__main__': mutex = threading.Lock() t1 = MyThread(100,5) t1.start() t2 = MyThread(200,1) t2.start()结果:

总结

在多线程开发中,全局变量是多个线程都共享的数据,而局部变量等是各自线程的,是非共享的

  
转载请注明原文地址: https://www.6miu.com/read-14605.html

最新回复(0)