import time import threading def sing(): """唱歌5秒""" for i in range(5): print("--正在唱---") time.sleep(1) def dance(): 子线程 for i in range(5): print("--正在跳舞---") time.sleep(1) def main(): t1 = threading.Thread(target=sing) t2 = threading.Thread(target=dance) 创建对象 t1.start() t2.start() 主线程 创建子线程 print(threading.enumerate()) #运行时查看有几个线程 如果没有延时不确定包含几个线程
if __name__ == ‘__main__‘:
main()
调用start()的时候子线程开启 函数代买执行完子线程结束
并行:真的多任务 并发:假的多任务
线程:程序运行起来 执行代码的东西
主线程 子线程:https://www.bilibili.com/video/av73705797?p=2
通过集成thread来创建线程
import threading import time class MyThread(thrading.Thread): def run(self): #必须写run for i in range(3): time.sleep(1) msg = "I‘m"+self.name+@+str(i) print(msg) if __name__=‘__main__‘: t = MyThread() t.start 自动调用 run 方法
多个线程之间共享全局变量
num= 100 num=[11,22] def test(): global num num += 100 def test1(): nums.append(33) #nums+=[100,200]#需要加global print(num,nums) test() test1() print(num,nums) #改变其本身(内存地址)时需要加global 当改变其里面内容(不改变id)b不用加global
import time import threading g_num = 100 def test1(): global g_num g_num +=1 print("---->%d"%g_num) def test2(): print("---->%d"%g_num) def main(): t1 = threading.Thread(target=test1) t2 = threading.Thread(target=test2) t1.start() time.sleep(1) t2.start() if __name__ == ‘__main__‘: main() -->101 --->101
多线程共享全局变量--args参数 需要元组类型 join()
import time import threading g_num = 100 def test1(num): global g_num
for i in num: g_num +=1 print("---->%d"%g_num) def test2(): print("---->%d"%g_num) def main(): t1 = threading.Thread(target=test1,args=(100,)) t2 = threading.Thread(target=test2) t1.start() time.sleep(1) t2.start() if __name__ == ‘__main__‘: main()
import time
import random
from threading import Thread,currentThread
dic = {}
def func(i):
t = currentThread()
time.sleep(random.random())
dic[t.ident] = i**2
t_lst = []
for i in range(1,11):
t = Thread(target=func,args=(i,))
t.start()
t_lst.append(t)
for t in t_lst:
t.join()
print(dic[t.ident])
多线程可以有多个锁
死锁 可以添加超时时间解决
import json import time from multiprocessing import Process,Lock def search_ticket(name): with open(‘ticket‘,encoding=‘utf-8‘) as f: dic = json.load(f) print(‘%s查询余票为%s‘%(name,dic[‘count‘])) def buy_ticket(name): with open(‘ticket‘,encoding=‘utf-8‘) as f: dic = json.load(f) time.sleep(2) if dic[‘count‘] >= 1: print(‘%s买到票了‘%name) dic[‘count‘] -= 1 time.sleep(2) with open(‘ticket‘, mode=‘w‘,encoding=‘utf-8‘) as f: json.dump(dic,f) else: print(‘余票为0,%s没买到票‘ % name) def use(name,lock): search_ticket(name) print(‘%s在等待‘%name) # lock.acquire() # print(‘%s开始执行了‘%name) # buy_ticket(name) # lock.release() with lock: print(‘%s开始执行了‘%name) buy_ticket(name) if __name__ == ‘__main__‘: lock = Lock() l = [‘alex‘,‘wusir‘,‘baoyuan‘,‘taibai‘] for name in l: Process(target=use,args=(name,lock)).start()
from threading import Lock,Thread
noodle_lock = Lock()
fork_lock = Lock()
def eat1(name):
noodle_lock.acquire() # 阻塞 宝元等面
print(‘%s拿到面了‘%name)
fork_lock.acquire()
print(‘%s拿到叉子了‘ % name)
print(‘%s吃面‘%name)
fork_lock.release()
print(‘%s放下叉子了‘ % name)
noodle_lock.release()
print(‘%s放下面了‘ % name)
def eat2(name):
fork_lock.acquire() # 阻塞 wu‘sir等叉子
print(‘%s拿到叉子了‘ % name)
noodle_lock.acquire()
print(‘%s拿到面了‘%name)
print(‘%s吃面‘%name)
noodle_lock.release()
print(‘%s放下面了‘ % name)
fork_lock.release()
print(‘%s放下叉子了‘ % name)
Thread(target=eat1,args = (‘alex‘,)).start()
Thread(target=eat2,args = (‘wusir‘,)).start()
Thread(target=eat1,args = (‘baoyuan‘,)).start()
多线程版聊天 udp:
https://www.bilibili.com/video/av73705797?p=10
原文:https://www.cnblogs.com/qj696/p/12329264.html