1.线程的创建
from threading import Thread
import time
# 如果多个线程执行的都是同一个函数,各自之间不会有影响,各是各的
def test():
print('---昨晚喝多了---')
time.sleep(1)
if __name__=='__main__':
for i in range(5):
t = Thread(target=test)
t.start()
2.使用Thread子类创建线程
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(5):
time.sleep(1)
msg = 'I am' + self.name + '@' + str(i)
print(msg)
if __name__=='__main__':
t = MyThread()
t.start()
僵尸进程:本该清理线程的进程,却没有清理的进程
孤儿进程:没有进程来清理线程
3.线程的执行顺序
线程的创建顺序是有序的,但线程的执行顺序是无序的
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = 'I am' +self.name+' @ '+str(i)
print(msg)
def test():
for i in range(5):
t = MyThread()
t.start()
if __name__=='__main__':
test()
3.线程中的全局变量
from threading import Thread
import time
g_num = 100
def work1():
global g_num
for i in range(3):
g_num += 1
print('--in work1, g_num is %s--' % g_num)
def work2():
print('--in work2, g_num is %s--' % g_num)
if __name__=='__main__':
print('--线程执行之前,g_num is %s--' % g_num)
t1 = Thread(target=work1)
t1.start()
# 延时一会,保证t1线程中的事情做完
time.sleep(1)
t2 = Thread(target=work2)
t2.start()
4.互斥锁
(1)互斥锁的定义
# 导入需要的模块
from threading import Thread, Lock
# 创建锁
mutex = Lock()
# 上锁
mutex.acquire()
# 解锁
mutex.release()
(2)案例
from threading import Thread, Lock
import time
g_num = 0
def test1():
global g_num
# 这个线程与test2线程都在抢着上锁.如果有一方成功上锁,那么导致另外一方堵塞,直到这个锁被解开
for i in range(1000000):
mutex.acquire()
g_num += 1
mutex.release()
print('---test1 --g_num is %s' % g_num)
def test2():
global g_num
for i in range(1000000):
mutex.acquire()
g_num += 1
mutex.release()
print('--test2-- g_num is %s' % g_num)
if __name__=='__main__':
# 创建一把互斥锁
mutex = Lock()
p1 = Thread(target=test1)
p1.start()
p2 = Thread(target=test2)
p2.start()
5.同步
按一定的顺序执行代码
from threading import Lock, Thread
import time
class Task1(Thread):
def run(self):
while True:
if lock1.acquire():
print('--Task1--')
time.sleep(0.5)
lock2.release()
class Task2(Thread):
def run(self):
while True:
if lock2.acquire():
print('--Task2--')
time.sleep(0.5)
lock3.release()
class Task3(Thread):
def run(self):
while True:
if lock3.acquire():
print('--Task3--')
time.sleep(0.5)
lock1.release()
if __name__=='__main__':
lock1 = Lock()
lock2 = Lock()
lock2.acquire()
lock3 = Lock()
lock3.acquire()
t1 = Task1()
t2 = Task2()
t3 = Task3()
t1.start()
t2.start()
t3.start()
6.生产者与消费者模式
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 += 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(0.5)
if __name__=='__main__':
queue = Queue()
for i in range(200):
queue.put('初始产品' + str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
7.ThreadLocal
import threading
# 创建全局ThreadLocal对象
local_school = threading.local()
def process_student():
# 获取当前线程关联的student
std = local_school.student
print('Hello, %s (in %s)' %(std, threading.current_thread().name))
def process_thread(name):
# 绑定ThreadLocal的student
local_school.student = name
process_student()
t1 = threading.Thread(target=process_thread, args=('老王',), name='Thread-A')
t2 = threading.Thread(target=process_thread, args=('老李',), name='Thread-B')
t1.start()
t2.start()
8.异步
from multiprocessing import Pool
import os
import time
def test():
print('--进程池中的进程--pid=%d,ppid=%d--' %(os.getpid(), os.getppid()))
for i in range(3):
print('---%d---' %i)
time.sleep(1)
return 'hahaha'
def test2(args):
print('--callback func--pid=%d--' %os.getpid())
print('--callback func--args=%s--' %args)
if __name__=='__main__':
pool = Pool(3)
pool.apply_async(func=test, callback=test2)
while True:
time.sleep(1)
print('--主进程--pid=%d--' %os.getpid())