python multithreading_thread, threading and queue queue

1. Python multi-threading_thread, threading

Two commonly used modules in Python3 threads are:

  • _thread
  • threading (recommended)

The thread module has been deprecated. Users can use the threading module instead. Therefore, the "thread" module can no longer be used in Python3. For compatibility, Python3 renames thread to "_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("主进程退出")

2. python queue queue

It is not directly related to multi-threading. The queue supports first-in-first-out (default), first-in-last-out, etc.;

Put it here together with multi-threading, and write an exercise to use multi-threading to read the data in the queue until there is no more data.

Note: Multi-threads must lock when acquiring queue data.

#!/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 ("退出主线程")

Guess you like

Origin blog.csdn.net/Mr_wilson_liu/article/details/130479411