多线程编程:Python中的多线程编程函数
发布时间:2023-06-08 10:52:22
多线程编程是指同时运行多个线程执行不同的任务。在Python中,可以使用threading模块来进行多线程编程。
threading模块提供了Thread类来创建并启动一个新线程。以下是一些常用的多线程编程函数:
1. threading.Thread(target=函数名, args=(参数1, 参数2, ...)):创建并启动一个新线程,并指定运行的函数和参数。例如:
import threading
def hello(name):
print("Hello " + name)
t = threading.Thread(target=hello, args=("world",))
t.start()
# 输出:Hello world
2. threading.current_thread():返回当前线程对象。
3. threading.active_count():返回当前存活的线程数。
4. threading.enumerate():返回当前存活的所有线程对象。
5. threading.Lock():创建一个锁对象,用于线程同步。例如:
import threading
lock = threading.Lock()
def hello(name):
lock.acquire()
print("Hello " + name)
lock.release()
t1 = threading.Thread(target=hello, args=("world",))
t2 = threading.Thread(target=hello, args=("Python",))
t1.start()
t2.start()
# 输出:
# Hello world
# Hello Python
在以上代码中,由于两个线程要共同使用print函数输出内容,为了避免输出混乱,使用了锁对象进行线程同步。
6. threading.Timer(interval, 函数名, args=(参数1, 参数2, ...)):创建一个定时器对象,用于定时执行指定函数。例如:
import threading
def hello():
print("Hello world")
t = threading.Timer(5.0, hello)
t.start()
# 5秒后输出:Hello world
在以上代码中,定时器对象t会在5秒后执行hello函数。
总的来说,多线程编程可以提高程序的执行效率,但需要注意线程同步的问题。在Python中,可以使用threading模块提供的函数来实现多线程编程。
