线程相当于程序中的“指向箭头”
一、创建方式
from threading import Thread
import time
def test():
print(‘-----啊哈-----‘)
time.sleep(1)
for i in range(5):#主线程执行循环,创建出5个子线程指向函数
t = Thread(target = test)
t.start()
#主线程执行完循环后停滞,等子线程都执行完毕后才会结束程序
二、互斥锁,用于解决资源争夺问题
from threading import Thread,Lock
import time
num = 0
def test1():
global num
for i in range(100000):
#两个线程争抢上锁,如果一方上锁,另一方会堵塞(一直等待),直到解锁
mutex.acquire()
num += 1
#用来解锁,接下来会让因这个锁而堵塞的线程继续争抢上锁
mutex.release()
print(‘===test1===num = %d‘%num)
def test2():
global num
for i in range(100000):
mutex.acquire()
num += 1
mutex.release()
print(‘===test2===num = %d‘%num)
#创建一把互斥锁,默认没有上锁
mutex = Lock()
p1 = Thread(target = test1)
p1.start()
p2 = Thread(target = test2)
p2.start()
print(‘当前num = %d‘%num)
三、聊天软件demo(需要模拟端收发信息)
from socket import *
from threading import Thread
#收数据
def recvData():
while True:
recvInfo = udpSocket.recvfrom(1024)
print(‘\r>>%s :%s\n<<‘%(str(recvInfo[1]),recvInfo[0].decode(‘gb2312‘)))
#发数据
def sendData():
while True:
sendInfo = input(‘<<‘)
udpSocket.sendto(sendInfo.encode(‘gb2312‘),(ipInfo,portInfo))
udpSocket = None
ipInfo = ‘‘
portInfo = 0
def main():
global udpSocket
global ipInfo
global portInfo
udpSocket = socket(AF_INET,SOCK_DGRAM)
udpSocket.bind((‘‘,5687))
ipInfo = input(‘请输入目标IP:‘)
portInfo = int(input(‘请输入目标端口:‘))
sr = Thread(target = recvData)
ss = Thread(target = sendData)
sr.start()
ss.start()
sr.join()
ss.join()
if __name__ == ‘__main__‘:
main()
原文:https://www.cnblogs.com/dalun101/p/9367609.html