python多线程_thread、threading和队列queue

一、python多线程_thread、threading

Python3 线程中常用的两个模块为:

  • _thread
  • threading(推荐使用)

thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3 将 thread 重命名为 "_thread"

#多线程,用函数,或者用类包装线程对象
#学习路径:https://www.runoob.com/python3/python3-multithreading.html

import time
import _thread
import threading

def print_time(threadName, delay):
    time.sleep(delay)
    # print(threadName)
    count = 0
    while count<3:
        count +=1
        print("%s:%s"%(threadName,time.ctime(time.time())))

#方法一,用函数来起多线程
def method_thread():
    try:
        _thread.start_new_thread(print_time,("Thread-1",2, ))
        _thread.start_new_thread(print_time,("Thread-2",4, ))
        print("启动两个线程成功")
    except:
        print("启动线程失败")
    while 1:
        pass

#方法二,用类来起多线程
class my_threading(threading.Thread):
    def __init__(self,threadId, name, delay, threadLock):
        threading.Thread.__init__(self)
        self.threadId = threadId
        self.name = name
        self.delay = delay
        self.threadLock = threadLock

    def run(self):
        print("开始线程:"+self.name)
        # 获取锁,用于线程同步
        self.threadLock.acquire()
        print_time(self.name, self.delay)
        # 释放锁,开启下一个线程
        self.threadLock.release()
        # print("退出线程:"+self.name)



if __name__ == '__main__':
    # method_thread()
    #定义锁
    threadLock1 = threading.Lock()
    #定义线程组
    threads = []
    thread1 = my_threading(1,'thread_1',1, threadLock1)
    thread2 = my_threading(2,'thread_2',1, threadLock1)
    threads.append(thread1)
    threads.append(thread2)

    #启用线程
    for i in threads:
        i.start()
    #等待线程执行结束
    for i in threads:
        i.join()
    print("主进程退出")

二、python队列queue

跟多线程没直接关系,queue队列支持先进先出(默认)、也支持先进后出等;

放在这里跟多线程一起,配合写个练习,用多线程去读队列里面的数据,直到没有数据了。

注意:多线程获取队列数据要加锁。

#!/usr/bin/python3

import queue
import threading
import time


class myThread (threading.Thread):
    def __init__(self, threadID, name, my_queue, queueLock):
        '''
        :param threadID: 线程id
        :param name: 线程名字
        :param my_queue: 队列
        :param queueLock: 锁
        '''
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.my_queue = my_queue
        self.queueLock = queueLock
    def run(self):
        print ("开启线程:" + self.name)
        process_data(self.name, self.my_queue, self.queueLock)
        print ("退出线程:" + self.name)


#读队列数据函数
def process_data(threadName, my_queue, queueLock):
    '''
    :param threadName: 线程名称
    :param my_queue: 队列
    :param queueLock: 锁
    :return:
    '''
    # #如果数据读完了,就退出
    while not workQueue.empty():
        queueLock.acquire()
        data = my_queue.get()
        queueLock.release()
        print ("%s processing read ---- %s" % (threadName, data))
        time.sleep(1)


if __name__ == '__main__':
    threadList = ["Thread-1", "Thread-2", "Thread-3"]
    nameList = ["One", "Two", "Three", "Four", "Five", "six"]

    # 定义队列,队列长度为10
    workQueue = queue.Queue(10)
    # 填充队列
    for word in nameList:
        workQueue.put(word)

    #定义锁、线程组,线程自定义id
    queueLock = threading.Lock()
    threads = []
    threadID = 1
    # 创建新线程组
    for tName in threadList:
        thread = myThread(threadID, tName, workQueue, queueLock)
        thread.start()
        threads.append(thread)
        threadID += 1
    # 等待所有线程完成
    for t in threads:
        t.join()
    print ("退出主线程")

猜你喜欢

转载自blog.csdn.net/Mr_wilson_liu/article/details/130479411
今日推荐