python 使用多线程

python 使用多线程

什么是线程?

在软件编程中,线程是具有独立指令集的最小执行单元。它是进程的一部分,并在共享程序相同的可运行资源(如内存)中运行。线程有一个起点、一个执行序列和一个结果。它有一个指令指针,该指针保存线程的当前状态,并控制下一步以什么顺序执行什么。

举个通俗的例子,进程相当于工厂的多个独立生产成品的车间,线程相当于每个车间中生产的各个环节。

什么是计算机科学中的多线程?

一个进程可以并行执行多个线程的能力称为多线程。理想情况下,多线程可以显著提高任何程序的性能。Python多线程机制非常友好,易于学会。

多线程的优势

一个进程的所有线程都可以访问它的全局变量。如果一个全局变量在一个线程中发生变化,那么它对其他线程也是可见的。线程也可以有自己的局部变量。

多线程的缺点

在单处理器系统上,多线程不会影响计算速度。由于管理线程的开销,性能可能会下降。

多线程增加了程序的复杂性,因此也增加了调试的难度。

python 中多线程模块

python3中多线程是threading.

  • threading.activeCount(): 找出活动线程对象的总数。
  • threading.currentThread(): 确定调用方的线程控件中的线程对象的数量。
  • threading.enumerate(): 提供当前活动的线程对象的完整列表。

除了上述方法之外,threading模块还提供了Thread类,您可以尝试使用它来实现线程。它是Python多线程的面向对象变体。

The <Thread> class publishes the following methods.

Class Methods Method Description
run(): 它是任何线程的入口函数。
start(): start()方法在调用时触发一个线程。
join([time]): join()方法允许程序等待线程终止。
isAlive(): isAlive()方法验证线程是否是活动的。
getName(): getName()方法检索线程的名称。
setName(): setName() 方法的作用是更新线程的名称。

使用threading模块实现线程的步骤

您可以按照以下步骤使用threading模块实现一个新线程。

  1. Thread类构造一个子类。
  2. 覆盖 init__(self [,args])方法,根据需求提供参数。
  3. 接着重写run(self [,args])方法来编写线程的业务逻辑。

一旦定义了新的Thread子类,就必须实例化它来启动一个新线程。然后,调用start()方法来初始化它。它最终将调用run()方法来执行任务逻辑。

基础多线程例子

#Python multithreading example to print current date.
#1. Define a subclass using threading.Thread class.
#2. Instantiate the subclass and trigger the thread.

import threading
import datetime

class myThread (threading.Thread):
    def __init__(self, name, counter):
        threading.Thread.__init__(self)
        self.threadID = counter
        self.name = name
        self.counter = counter
    def run(self):
        print("\nStarting " + self.name)
        print_date(self.name, self.counter)
        print("Exiting " + self.name)

def print_date(threadName, counter):
    datefields = []
    today = datetime.date.today()
    datefields.append(today)
    print("{}[{}]: {}".format( threadName, counter, datefields[0] ))

# Create new threads
thread1 = myThread("Thread", 1)
thread2 = myThread("Thread", 2)

# Start new Threads
thread1.start()
thread2.start()

thread1.join()
thread2.join()
print("\nExiting the Program!!!")

程序输出

Starting Thread
Thread[1]: 2019-04-28
Exiting Thread

Starting Thread
Thread[2]: 2019-04-28
Exiting Thread

Exiting the Program!!!

Python多线程——同步线程

threading模块具有实现锁的内置功能,允许同步线程。需要使用锁定来控制对共享资源的访问,以防止损坏或丢失数据。

你可以调用Lock()方法来应用锁,它会返回新的锁对象。然后,您可以调用lock对象的acquire(blocking)方法来强制线程同步运行。

可选的阻塞(blocking)参数指定线程是否等待获取锁。

  • blocking = 0: 如果线程未能获得锁,则立即返回零值,如果锁成功,则返回一值。
  • blocking = 1: 线程阻塞并等待锁被释放。

lock对象的release()方法用于在不再需要锁时释放锁。

多线程锁的例子

#Python multithreading example to demonstrate locking.
#1. Define a subclass using threading.Thread class.
#2. Instantiate the subclass and trigger the thread. 
#3. Implement locks in thread's run method. 

import threading
import datetime

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, name, counter):
        threading.Thread.__init__(self)
        self.threadID = counter
        self.name = name
        self.counter = counter
    def run(self):
        print("\nStarting " + self.name)
        # Acquire lock to synchronize thread
        threadLock.acquire()
        print_date(self.name, self.counter)
        # Release lock for the next thread
        threadLock.release()
        print("Exiting " + self.name)

def print_date(threadName, counter):
    datefields = []
    today = datetime.date.today()
    datefields.append(today)
    print("{}[{}]: {}".format( threadName, counter, datefields[0] ))

threadLock = threading.Lock()
threads = []

# Create new threads
thread1 = myThread("Thread", 1)
thread2 = myThread("Thread", 2)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for thread in threads:
    thread.join()

print("\nExiting the Program!!!")

程序输出

Starting Thread
Thread[1]: 2019-04-28
Exiting Thread

Starting Thread
Thread[2]: 2019-04-28
Exiting Thread

Exiting the Program!!!

参考

posted @ 2020-03-12 10:19  songbiao  阅读(613)  评论(0编辑  收藏  举报