python_多线程

http://www.jb51.net/article/55317.htm

http://www.cnblogs.com/fnng/p/3670789.html

Python 的多线程有两种实现方法:

函数,线程类

1.函数

调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么

复制代码代码如下:

# -*- coding: utf-8 -*-
import thread
def f(name):
  #定义线程函数
  print "this is " + name
 
if __name__ == '__main__':
  thread.start_new_thread(f, ("thread1",))
  #用start_new_thread()调用线程函数和其他参数
  while 1:
    pass

不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用 while 1 这种方法解决。

2.线程类

调用 threading 模块,创建 threading.Thread 的子类来得到自定义线程类。

复制代码代码如下:

# -*- coding: utf-8 -*-
import threading
class Th(threading.Thread):
  def __init__(self, name):
    threading.Thread.__init__(self)
    self.t_name = name
    #调用父类构造函数
 
  def run(self):
    #重写run()函数,线程默认从此函数开始执行
    print "This is " + self.t_name
 
if __name__ == '__main__':
  thread1 = Th("Thread_1")
  thread1.start()
  #start()函数启动线程,自动执行run()函数

threading.Thread 类的可继承函数:
getName() 获得线程对象名称
setName() 设置线程对象名称
join() 等待调用的线程结束后再运行之后的命令
setDaemon(bool) 阻塞模式, True: 父线程不等待子线程结束, False 等待,默认为 False
isDaemon() 判断子线程是否和父线程一起结束,即 setDaemon() 设置的值
isAlive() 判断线程是否在运行

实例

复制代码代码如下:

import threading
import time
class Th(threading.Thread):
  def __init__(self, thread_name):
    threading.Thread.__init__(self)
    self.setName(thread_name)
 
  def run(self):
    print "This is thread " + self.getName()
    for i in range(5):
      time.sleep(1)
      print str(i)
    print self.getName() + "is over"

join() 阻塞等待

复制代码代码如下:

if __name__ == '__main__':
    thread1 = Th("T1 ")
    thread1.start()
    #thread1.join()
    print "main thread is over"

不带 thread1.join() ,得到如下结果:

复制代码代码如下:

This is thread T1
main thread is over
0
1
2
T1 is over

不等待 thread1 完成,执行之后语句。
加了 thread1.join() ,得到如下结果:
复制代码代码如下:

This is thread T1
0
1
2
T1 is over
main thread is over

阻塞等待 thread1 结束,才执行下面语句

主线程等待

复制代码代码如下:

if __name__ == '__main__':
  thread1 = Th("T1 ")
  thread1.setDaemon(True)
  #要在线程执行之前就设置这个量
  thread1.start()
  print "main thread is over"

报错: Exception in thread T1 (most likely raised during interpreter shutdown):
也就是主线程不等待子线程就结束了。

多个子线程

复制代码代码如下:

if __name__ == '__main__':
    for i in range(3):
        t = Th(str(i))
        t.start()
    print "main thread is over"

这里的 t 可同时处理多个线程,即 t 为线程句柄,重新赋值不影响线程。

这里奇怪的是,运行 t.run() 时,不会再执行其他线程。虽不明,还是用 start() 吧。暂且理解为 start() 是非阻塞并行的,而 run 是阻塞的。

线程锁

threading 提供线程锁,可以实现线程同步。

复制代码代码如下:

import threading
import time
class Th(threading.Thread):
  def __init__(self, thread_name):
    threading.Thread.__init__(self)
    self.setName(thread_name)
 
  def run(self):
    threadLock.acquire()
    #获得锁之后再运行
    print "This is thread " + self.getName()
    for i in range(3):
      time.sleep(1)
      print str(i)
    print self.getName() + " is over"
    threadLock.release()
    #释放锁
if __name__ == '__main__':
  threadLock = threading.Lock()
  #设置全局锁
  thread1 = Th('Thread_1')
  thread2 = Th('Thread_2')
  thread1.start()
  thread2.start()

得到结果:

复制代码代码如下:

This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over
import threading
from time import ctime,sleep


def music(func):
    for i in range(2):
        print "I was listening to %s. %s" %(func,ctime())
        sleep(1)

def move(func):
    for i in range(2):
        print "I was at the %s! %s" %(func,ctime())
        sleep(1)

threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)

if __name__ == '__main__':
    for t in threads:

        t.setDaemon(False)
        t.start()
    t.join()
    print "all over %s" %ctime()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 很抱歉,我之前回答的还是这个问题。以下是一个稍微复杂一点的 Python 多线程实例,可以用来计算一个矩阵的乘积: ```python import threading import numpy as np # 定义矩阵的大小 MATRIX_SIZE = 1000 # 初始化两个随机矩阵 matrix_a = np.random.rand(MATRIX_SIZE, MATRIX_SIZE) matrix_b = np.random.rand(MATRIX_SIZE, MATRIX_SIZE) # 初始化结果矩阵 result_matrix = np.zeros((MATRIX_SIZE, MATRIX_SIZE)) # 定义一个函数,用来计算矩阵的乘积 def multiply(start, end): for i in range(start, end): for j in range(MATRIX_SIZE): for k in range(MATRIX_SIZE): result_matrix[i][j] += matrix_a[i][k] * matrix_b[k][j] # 定义线程数量 NUM_THREADS = 4 # 计算每个线程需要计算的行数 rows_per_thread = MATRIX_SIZE // NUM_THREADS # 创建线程列表 threads = [] # 启动线程 for i in range(NUM_THREADS): start = i * rows_per_thread end = (i + 1) * rows_per_thread t = threading.Thread(target=multiply, args=(start, end)) threads.append(t) t.start() # 等待所有线程结束 for t in threads: t.join() # 检查结果是否正确 expected_result = np.dot(matrix_a, matrix_b) assert np.array_equal(result_matrix, expected_result) # 输出 Done 表示程序执行完毕 print("Done") ``` 这个例子首先初始化两个随机矩阵,然后定义一个函数 multiply,用来计算这两个矩阵的乘积。然后,它将矩阵分成若干个部分,每个部分分配给一个线程来计算。最后,它等待所有线程结束,检查结果是否正确,并输出 Done 表示程序执行完毕。 希望这个例子能够帮助您更好地理解 Python 多线程的使用方法。 ### 回答2: Python多线程实例是指在Python编程语言中使用多线程进行并发编程的实例。在Python中,可以使用内置的threading模块来创建和管理多线程。 通过创建多线程,可以在程序中同时执行多个任务。这对于需要同时处理多个任务的情况非常有用。例如,在下载大文件时,可以使用多线程同时下载多个文件,加快下载速度。此外,多线程还可以用于处理网络请求、图像处理、数据处理等耗时操作,提高程序的运行效率。 使用Python多线程的主要步骤如下: 1. 导入threading模块。 ``` import threading ``` 2. 创建一个线程对象,可以通过继承threading.Thread类或使用threading.Thread()函数创建。 ``` class MyThread(threading.Thread): def __init__(self, name): super().__init__() self.name = name def run(self): # 线程执行的代码 print("Hello, " + self.name) thread1 = MyThread("Thread 1") thread2 = threading.Thread(target=func, args=("Thread 2",)) ``` 3. 启动线程。 ``` thread1.start() thread2.start() ``` 4. 等待线程结束。 ``` thread1.join() thread2.join() ``` 以上代码演示了两种创建多线程的方法:1)继承threading.Thread类,重写run方法;2)使用函数作为线程的执行内容。线程的启动调用start()方法,等待线程结束使用join()方法。 需要注意的是,Python多线程的并发程度受到全局解释器锁(GIL)的限制,因此对于计算密集型的任务,多线程并不能发挥出多核的优势。如果需要发挥多核性能,可以考虑使用多进程编程。 总之,Python多线程实例能够提高程序的并发处理能力,适用于需要同时处理多个任务的场景。通过合理设计线程的数量和任务分配,可以提高程序的性能和效率。 ### 回答3: Python多线程实例是指通过使用多线程的技术来提高Python程序的运行效率和性能。在Python中,我们可以使用threading模块来实现多线程多线程技术可以同时执行多个任务,提高程序的运行速度。在Python中,我们可以通过创建Thread对象并调用start()方法来启动一个线程。下面是一个简单的例子: import threading def print_numbers(): for i in range(1, 11): print(i) def print_letters(): for letter in ['A', 'B', 'C', 'D', 'E']: print(letter) # 创建两个线程 t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_letters) # 启动两个线程 t1.start() t2.start() # 等待两个线程结束 t1.join() t2.join() # 主线程继续执行 print("主线程结束") 以上代码中,我们创建了两个线程,分别执行print_numbers()和print_letters()函数。通过调用start()方法启动线程,并通过join()方法等待两个线程执行完毕。最后,主线程继续执行并打印出一段文字。 需要注意的是,多线程并不一定能提高程序的运行速度,因为在Python中,全局解释器锁(Global Interpreter Lock,GIL)会限制同一时间只能有一个线程执行Python字节码。因此,在CPU密集型任务中,多线程并不能真正实现并行计算。但是,在IO密集型任务中,多线程能够提高程序的运行效率。 总结起来,Python多线程实例可以通过使用threading模块来实现。多线程能够提高IO密集型任务的运行效率,但在CPU密集型任务中并不能真正实现并行计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值