Python threading多线程
目录
1、
2、Lock
1、
# encoding: utf-8
import threading
import time
from queue import Queue
def thread_1_job():
print("Thread-1 start\n")
for i in range(10):
time.sleep(0.3)
print("Thread-1 finished\n")
def thread_2_job():
print("Thread-2 start\n")
for c in "ABCDEFG":
time.sleep(0.3)
print("Thread-2 finished\n")
def queue_job(list,q):
for i in range(len(list)):
list[i] = list[i] **2
q.put(list)
"""threading多线程的常用方法"""
def main_1():
# 添加一个线程,并添加线程所需函数
thread = threading.Thread(target=thread_1_job)
# 运行线程
thread.start()
# 当前激活的线程数
print(threading.active_count())
# 当前激活线程的详细信息
print(threading.enumerate())
# 正在运行的线程详细信息
print(threading.current_thread())
"""join主线程等待线程执行完毕"""
def main_join():
# 添加一个线程,并添加线程所需函数
# target= thread_job()不能带括号
thread_1 = threading.Thread(target=thread_1_job,name='Thread-1')
thread_2 = threading.Thread(target=thread_2_job,name="Thread-2")
thread_1.start()
thread_2.start()
# 等待线程运行结束后在去继续向后执行
thread_1.join()
thread_2.join()
print("all threads is done !!")
"""queue多线程分批处理数据"""
def main_queue(data):
# 存放线程的返回值
q = Queue()
threads = []
#
for i in range(4):
# queue_job没有括号,args是向线程传递的参数
t = threading.Thread(target=queue_job,args=(data[i],q))
t.start()
threads.append(t)
for t in threads:
t.join()
result = []
for _ in range(4):
# 该方法只能拿出一个值,并且有序
r = q.get()
result.append(r)
print(result)
if __name__ == '__main__':
# main_1()
# main_join()
data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]
main_queue(data)
2、Lock
# encoding: utf-8
import threading
import time
from queue import Queue
"""处理共享变量"""
def job1():
global A,lock
# 开始加锁
lock.acquire()
for i in range(2):
A += 1
print("job_1 num = %s " % A)
# 释放锁
lock.release()
def job2():
global A,lock
# 开始加锁
lock.acquire()
for i in range(2):
A += 10
print("job_2 num =%s " % A)
# 释放锁
lock.release()
if __name__ == '__main__':
"""实现将job1 打印完后再打印 job2"""
A = 0 # 全局变量
lock = threading.Lock()
t1 = threading.Thread(target=job1)
t2 = threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()
还没有评论,来说两句吧...