多任务指的是同时做多个任务
单核cpu里执行多任务时使用的是基于cpu的轮转方式,给各个任务分配时间片,在不同进程之间快速切换,即所谓并发,在同一时间段内执行 多个任务。像时间穿梭者快速在不同空间穿梭,在外部看起来他在哪个空间也没离开过,并把每个空间的任务都完成了。
并行是多核cpu运行任务,在同一时间点执行。
并发的实际情况是:多个进程被加载到内存里,当cpu要执行哪个进程时,他相关的数据会被调到缓冲区,切换时又被退回到内存里。
线程:一个进程里的一条代码执行流程。主线程是默认存在的线程,子线程是在主线程被创建的线程。
多线程的目的是提高cpu的利用率。
1.第一种创建子进程的方法
import threading
import time
def sing():
"""线程函数"""
for i in range(3):
print("唱歌"+str(i))
time.sleep(1)
def dance():
for i in range(3):
print("跳舞"+str(i))
time.sleep(1)
def main():
t1 = threading.Thread(target=sing)
t2 = threading.Thread(target=dance)#并没有这里真正创建#Thread实例对象。只是准备好,并将参数导入
#target = 线程函数名
t1.start()
t2.start()#start()方法才真正创建和启动该线程
if __name__ == '__main__':
main()
查看线程个数
``import threading
import time
g_num = 0
def work1():
for i in range (3):
global g_num
g_num += 1
print(g_num)
def work2():
print(g_num)
def main():
t1 = threading.Thread(target = work1)
t2 = threading.Thread(target=work2)
t1.start()
t2.start()
while True:
if len(threading.enumerate()) <= 1:
print("子进程结束")
break
else:
print("进程个数:" + str(len(threading.enumerate())))
if __name__ == '__main__':
main()
线程的运行顺序
import time
class MyThread(threading.Thread):
def run(self):
for i in range(5):
print(self.getName()+"@"+str(i))
time.sleep(1)
def main():
for i in range(5):
t1 = MyThread()
t1.start()
if __name__ == '__main__':
main()
'''
线程的顺序是随机的,即CPU随机的切换线程
多个线程共享全局变量
import threading
import time
g_num = 0
def work1(num):
global g_num
for i in range(num):
g_num += 1
print(“—-in work1, g_num is %d—”%g_num)
def work2(num):
global g_num
for i in range(num):
g_num += 1
print(“—-in work2, g_num is %d—”%g_num)
print(“—线程创建之前g_num is %d—”%g_num)
t1 = threading.Thread(target=work1, args=(1000000,))
t1.start()
t2 = threading.Thread(target=work2, args=(1000000,))
t2.start()
while len(threading.enumerate()) != 1:
time.sleep(1)
”’上面两句代码=
t1.join()
t2.join()
在t1/t2子线程执行完之前,主线程阻塞”’
print(“2个线程对同一个全局变量操作之后的最终结果是:%s” % g_num)
如果多个线程对同一个全局变量进行操作就会出现资源竞争情况,从而导致结果不正确。解决办法:互斥锁。
线程同步:协同步调,按照先后次序执行
import threading
import time
#
g_num = 0
#
def work1(num):
global g_num
for i in range(num):
g_num += 1
print(“—-in work1, g_num is %d—”%g_num)
#
#
def work2(num):
global g_num
for i in range(num):
g_num += 1
print(“—-in work2, g_num is %d—”%g_num)
#
#
print(“—线程创建之前g_num is %d—”%g_num)
#
t1 = threading.Thread(target=work1, args=(1000000,))
t1.start()
#
t2 = threading.Thread(target=work2, args=(1000000,))
t2.start()
#
while len(threading.enumerate()) != 1:
time.sleep(1)
#
print(“2个线程对同一个全局变量操作之后的最终结果是:%s” % g_num)
import threading
import time
g_num = 0
def work1(*args):
mutex,n =args
global g_num
for i in range(n):
mutex.acquire()
g_num += 1
mutex.release()
def work2(*args):
mutex, n = args
global g_num
for i in range(n):
mutex.acquire()
g_num += 1
mutex.release()
if name == ‘main‘:
n = 10000
mutex = threading.Lock()
t1 = threading.Thread(target=work1, args=(mutex,n))
t2 = threading.Thread(target=work1, args=(mutex,n))
t1.start()
t2.start()
while len(threading.enumerate()) != 1:
time.sleep(1)
print(g_num)
多线程聊天器 其实只有两个:接收消息和发送消息
import socket
import threading
def send_msg(udp_socket,ip,port):
while True:
msg = input(“>>>>”)
udp_socket.sendto(msg.encode(),(ip,port))
def recv_msg(udp_socket):
while True:
msg,adr = udp_socket.recvfrom(1024)
print(“%s<<<<<<%s”.rjust(100) % (msg.decode(),str(adr)))
def main():
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp_socket.bind((“”,7784))
ip = input(“ip:”)
port = int(input(“port:”))
t1 = threading.Thread(target = recv_msg,args=(udp_socket,))
t2 = threading.Thread(target=send_msg,args=(udp_socket,ip,port))
t1.start()
t2.start()
if name == ‘main‘:
main()
“`