欢迎访问宙启技术站
智能推送

Python多线程编程必须掌握的10个函数

发布时间:2023-06-21 10:31:56

Python作为一门具备着强大多线程编程能力的编程语言,对多线程编程的处理过于简捷明了。Python多线程编程的成功离不开各种细致精细的内置多线程函数。以下是10个必须掌握的Python多线程编程函数。

1. threading.Thread()

该函数使用的方法是在实例化时将要执行的函数和参数传递进去。例如:

import threading
def myfunc():
    print("This is my first thread.")

t = threading.Thread(target=myfunc)
t.start()

Thread()方法创建新的线程,这个线程在线程容器中排队等待执行。定义一个类继承自Thread,并且重载__init__()和run()方法可以使你创建自己的线程函数。

2. threading.active_count()

该函数用于获取当前的线程数。例如:

import threading
def myfunc():
    pass

t1 = threading.Thread(target=myfunc)
t2 = threading.Thread(target=myfunc)
t1.start()
t2.start()
print(threading.active_count())

以上代码将会输出3或4。因为主线程除了t1和t2之外还有其他线程在运行。

3. threading.currentThread()

该函数返回主线程对象,以便查看或操作主线程。例如:

import threading
def myfunc():
    print("threading.currentThread() returned", threading.currentThread())

t = threading.Thread(target=myfunc)
t.start()

输出:threading.currentThread() returned <_MainThread(MainThread, started 140236063215872)>

4. threading.enumerate()

该函数用来遍历线程容器中的线程对象。例如:

import threading
def myfunc():
    pass

t1 = threading.Thread(target=myfunc)
t2 = threading.Thread(target=myfunc)
t1.start()
t2.start()
for i in threading.enumerate():
    print(i.getName())

输出:MainThread t1 t2

5. threading.Lock()

该函数用于获取一个锁来控制多线程之间的访问。例如:

import threading
import time
def myfunc():
    with threading.Lock():
        print("Entering", threading.current_thread().name)
        time.sleep(2)
        print("Exiting", threading.current_thread().name)

t1 = threading.Thread(target=myfunc)
t2 = threading.Thread(target=myfunc)
t3 = threading.Thread(target=myfunc)
t1.start()
t2.start()
t3.start()

使用with语句能够让你忘记锁的释放,因为Python会自动释放锁。

6. threading.Event()

该函数创建一个事件对象,用于多个线程之间的同步。例如:

import threading

event = threading.Event()

def wait_for_event():
    print("waiting for event")
    event.wait()
    print("event received")

def your_func():
    print("your function!")
    event.set()

t1 = threading.Thread(target=wait_for_event)
t2 = threading.Thread(target=your_func)
t1.start()
t2.start()

输出: waiting for event your function! event received

7. threading.Barrier()

该函数用于创建一个阻塞屏障,使线程达到指定数量即会指示线程继续执行。例如:

import threading

barrier = threading.Barrier(3)

def myfunc():
    print("in func")
    barrier.wait()
    print("more func")

t1 = threading.Thread(target=myfunc)
t2 = threading.Thread(target=myfunc)
t3 = threading.Thread(target=myfunc)
t1.start()
t2.start()
t3.start()

输出:in func in func in func more func more func more func

8. threading.Condition()

该函数用于同时控制多个线程之间的操作。例如:

import threading
import time

condition_object = threading.Condition()

def t1_run():
    with condition_object:
        print("t1_run waiting ...")
        condition_object.wait()

    print("t1 entered.")

def t2_run():
    with condition_object:
        print("t2_run notifying ...")
        condition_object.notify()

t1 = threading.Thread(target=t1_run)
t2 = threading.Thread(target=t2_run)

t1.start()

time.sleep(2)  # Wait for t1 to start waiting.
t2.start()

t1.join()
t2.join()

输出:t1_run waiting ... t2_run notifying ... t1 entered.

9. threading.Semaphore()

该函数实现了 Semaphore 类,一个计数器用于控制允许并发进入代码段的线程数。例如:

import threading,time

semaphore = threading.Semaphore(2)

def func():
    semaphore.acquire()
    print(threading.current_thread().name, "acquired")
    time.sleep(5)
    semaphore.release()
    print(threading.current_thread().name, "released")

t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t3 = threading.Thread(target=func)

t1.start()
t2.start()
t3.start()

输出:

Thread-1 acquired

Thread-2 acquired

Thread-1 released

Thread-2 released

Thread-3 acquired

Thread-3 released

10. threading.Timer()

该函数用于设置一个定时器来执行指定的函数。例如:

import threading

def func():
    print("Timer --> Executing my function!")

t = threading.Timer(5.0, func)

t.start()

在5秒钟后输出:Timer --> Executing my function!

以上是多线程编程必须掌握的10个函数。它们不仅可以快捷高效地提高多线程编程的效率,而且可以大大提高多维任务的并行处理效率,同时避免竞争条件。同时也要注意,在程序设计过程中,要充分总结多线程编程中的经验,使用多线程的技巧,避免线程间的崩溃和资源浪费,使程序更加高效稳定。