多线程-threading
import time
from threading import Thread
#如果多个线程执行的是同一个函数的话,各自之间不会有影响
def test():
print("哈哈哈哈哈哈哈")
time.sleep(1)
for i in range(5):
t = Thread(target = test)
t.start()
哈哈哈哈哈哈哈
哈哈哈哈哈哈哈
哈哈哈哈哈哈哈
哈哈哈哈哈哈哈
哈哈哈哈哈哈哈
子类完成创建多线程
import time
import threading
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(3)
msg = "I am "+self.name +'@'+str(i)
print(msg)
if __name__ == '__main__':
t = MyThread()
t.start()
I am Thread-1@0
I am Thread-1@1
I am Thread-1@2
线程的执行顺序也是主线程和各个子线程随机执行,顺序不确定
线程对全局变量的修改
线程之间是共享全局变量的,进程间不共享变量,可以加一个flag来避免全局变量被修改。
使用互斥锁避免全局变量被修改
两个线程同时抢着上锁,如果有1方成功的上锁,那么导致另外一方会堵塞,一直等待这个锁被解开为止。所以叫互斥锁。
一般加锁会导致运行效率变低,所以,只在必要的地方加锁。以提高效率
#创建锁
mutex = threading.Lock()
#上锁
mutex.acquire()
#释放锁
mutex.release()
线程之间不共享全局变量
from threading import Thread
import time
import threading
def test1():
name = threading.current_thread().name
print("thread name is %s"%name)
g_num = 100
if name == "Thread-1":
g_num += 1
else:
time.sleep(2)
print("thread name is %s----g_num=%d"%(name,g_num))
p1 = Thread(target=test1)
p1.start()
p2 = Thread(target=test1)
p2.start()
____________________________________________________
thread name is Thread-1
thread name is Thread-1----g_num=101
thread name is Thread-2
thread name is Thread-2----g_num=100
死锁
要尽量避免死锁
设置超时
生产者与消费者模式
队列就是给生产者和消费者解耦用
import threading
import time
from queue import Queue
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize() < 1000:
for i in range(100):
count = count +1
msg = '生成产品'+str(count)
queue.put(msg)
print(msg)
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global queue
while True:
if queue.qsize() > 100:
for i in range(3):
msg = self.name + '消费了 '+queue.get()
print(msg)
time.sleep(1)
if __name__ == '__main__':
queue = Queue()
for i in range(500):
queue.put('初始产品'+str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
异步
GIL问题(全局解释器锁)
python中多进程的效率远远大于多线程