多任务
import threading
def dance():
for i in range(50):
print('我正在跳舞')
def sing():
for i in range(50):
print('我正在唱歌')
dance()
sing()
t1 = threading.Thread(target=dance())
t2 = threading.Thread(target=sing())
t1.start()
t2.start()
二、线程
2.1 多线程聊天
import socket, threading
s = socket.socket(AF_INET, socket.SPCK_DGRAM)
s.bind(('192.168.31.180', 9090))
def send_msg():
while True:
content = input('请输入要发生的信息:')
s.sendto(content.encode('utf8'),('192.168.31.199', 9000))
def rec_msg():
while True:
content = s.recvfrom(1024).decode('utf8')
print(content)
t1 = threading.Thread(target=send_msg)
t2 = threading.Thread(target=rec_msg)
t1.start()
t2.start()
2.2 多个线程共享全局变量
import threading
ticket = 20
def sell_ticket():
global ticket
while True:
if ticket > 0:
ticket -= 1
print(f'{
threading.current_thread().name}卖出一张票,还剩{
ticket}张')
else:
print(