Python多线程原理与用法实例剖析
什么是多线程?
在计算机科学中,线程是在单个程序中同时执行的一条指令序列。通常,单个程序可以拥有多个线程,这些线程共享程序的文件和数据,每个线程都可独立地执行指令。多线程使程序能够同时执行多个任务。
Python多线程原理
Python提供了threading
模块来实现多线程。在Python中,每个线程都有一个锁,这个锁可以防止多个线程同时进入同一个代码块,从而保证多线程的执行顺序。
Python中的GIL(全局解释器锁定)是一个线程锁,它防止在同一时间内多个Python线程同时执行Python字节码。因此,Python多线程主要用于I/O密集型任务,因为它们可能会因为等待I/O操作而阻塞,从而允许其他线程以并发方式工作。
Python多线程的用法
- 创建线程对象
t = threading.Thread(target=function, args=())
其中,target
参数是要执行的函数,args
参数是传递给函数的参数。
- 启动线程
t.start()
这个方法启动线程并开始执行。
- 等待线程结束
t.join()
这个方法等待已经启动的线程执行完毕。
示例1
下面是一个演示多线程用法的示例代码。这个代码启动了一个新的线程来计算1到1000的和,同时主线程继续执行其他任务。
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
sum = 0
for i in range(1, 1001):
sum += i
print(sum)
t = MyThread()
t.start()
print("Main thread")
输出:
Main thread
500500
示例2
下面是另一个示例代码,这个代码定义了两个线程,并模拟了一个叫做“竞赛”的任务。线程1和线程2在竞赛中不断增加自己的分数,直到分数达到最大值,然后输出获胜者的名称。
import threading
import time
class MyThread(threading.Thread):
def __init__(self, name, max_score):
threading.Thread.__init__(self)
self.name = name
self.max_score = max_score
self.score = 0
def run(self):
while self.score < self.max_score:
self.score += 1
print("%s: %d" % (self.name, self.score))
time.sleep(0.2)
print("%s wins!" % self.name)
t1 = MyThread("Thread 1", 50)
t2 = MyThread("Thread 2", 75)
t1.start()
t2.start()
t1.join()
t2.join()
print("Main thread")
输出:
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
Thread 1: 6
Thread 2: 6
Thread 1: 7
Thread 2: 7
Thread 1: 8
Thread 2: 8
Thread 1: 9
Thread 2: 9
Thread 1: 10
Thread 2: 10
Thread 1: 11
Thread 2: 11
Thread 1: 12
Thread 2: 12
Thread 1: 13
Thread 2: 13
Thread 1: 14
Thread 2: 14
Thread 1: 15
Thread 2: 15
Thread 1: 16
Thread 2: 16
Thread 1: 17
Thread 2: 17
Thread 1: 18
Thread 2: 18
Thread 1: 19
Thread 2: 19
Thread 1: 20
Thread 2: 20
Thread 1: 21
Thread 2: 21
Thread 1: 22
Thread 2: 22
Thread 1: 23
Thread 2: 23
Thread 1: 24
Thread 2: 24
Thread 1: 25
Thread 2: 25
Thread 1: 26
Thread 2: 26
Thread 1: 27
Thread 2: 27
Thread 1: 28
Thread 2: 28
Thread 1: 29
Thread 2: 29
Thread 1: 30
Thread 2: 30
Thread 1: 31
Thread 2: 31
Thread 1: 32
Thread 2: 32
Thread 1: 33
Thread 2: 33
Thread 1: 34
Thread 2: 34
Thread 1: 35
Thread 2: 35
Thread 1: 36
Thread 2: 36
Thread 1: 37
Thread 2: 37
Thread 1: 38
Thread 2: 38
Thread 1: 39
Thread 2: 39
Thread 1: 40
Thread 2: 40
Thread 1: 41
Thread 2: 41
Thread 1: 42
Thread 2: 42
Thread 1: 43
Thread 2: 43
Thread 1: 44
Thread 2: 44
Thread 1: 45
Thread 2: 45
Thread 1: 46
Thread 2: 46
Thread 1: 47
Thread 2: 47
Thread 1: 48
Thread 2: 48
Thread 1: 49
Thread 2: 49
Thread 2: 50
Thread 2 wins!
Main thread
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python多线程原理与用法实例剖析 - Python技术站