📜  python中线程的使用(1)

📅  最后修改于: 2023-12-03 15:19:31.712000             🧑  作者: Mango

Python中线程的使用

Python是一种支持多线程编程的编程语言。在Python中,使用threading模块可以轻松地创建线程,实现多任务并行处理。

线程的概念

线程是操作系统能够进行运算调度的最小单位,它被包含在进程中,是进程中的实际运作单位。线程是轻量级的进程,它可以与其他线程共享内存,这使得进程产生了轻量级的特性。

Python中的多线程
创建线程

在Python中,可以通过threading.Thread()函数创建线程。例:

import threading

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

if __name__ == '__main__':
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print("退出主线程")

在上述例子中,我们定义了一个类myThread继承了threading.Thread类,并实现了run()方法。通过实例化myThread类,我们创建了两个线程:thread1thread2。通过start()方法启动线程,通过join()方法等待线程结束。

线程同步

在并发编程中,线程同步是非常重要的。Python中可以通过threading.Lock()函数实现资源访问的同步。例:

import threading

class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("开始线程:" + self.name)
        threadLock.acquire()
        print_time(self.name, self.counter, 5)
        threadLock.release()
        print("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

threadLock = threading.Lock()

if __name__ == '__main__':
    threads = []
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
    thread1.start()
    thread2.start()
    threads.append(thread1)
    threads.append(thread2)
    for t in threads:
        t.join()
    print("退出主线程")

在上述例子中,我们使用了threading.Lock()函数创建了一个线程锁threadLock。在myThread中,我们通过acquire()方法获取锁,通过release()方法释放锁,以实现资源访问的同步。

线程优先级队列

在并发编程中,线程优先级队列用于确保高优先级的线程先被调度执行。Python中可以通过Queue.PriorityQueue()函数实现线程优先级队列。例:

import queue
import threading

class myThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        print("开始线程:" + self.name)
        process_data(self.name, self.q)
        print("退出线程:" + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.PriorityQueue(10)
threads = []
threadID = 1
exitFlag = 0

if __name__ == '__main__':
    # 创建新线程
    for tName in threadList:
        thread = myThread(threadID, tName, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1

    # 填充队列
    queueLock.acquire()
    for word in nameList:
        workQueue.put(word)
    queueLock.release()

    # 等待队列清空
    while not workQueue.empty():
        pass

    # 通知线程退出
    exitFlag = 1

    # 等待所有线程完成
    for t in threads:
        t.join()
    print("退出主线程")

在上述例子中,我们使用了queue.PriorityQueue()函数创建了一个线程优先级队列workQueue。在myThread中,我们通过get()put()方法从队列中获取和插入数据,以实现线程优先级调度。

小结

Python中多线程的创建和使用非常方便,可以充分发挥多核CPU的性能,提高程序的效率。在编写多线程代码时,需要注意线程同步和线程优先级队列的处理,以保证程序的正确性和性能。