【Python之旅】第七篇(一):再谈Python多线程

简介:

  主要是再进一步加深Python中关于多线程相关函数join()的理解以解多线程的执行过程。这里通过下面的例子来作进一步的说明。


1.多线程与主程序代码的执行顺序关系

    给出下面程序代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
 
import  threading
import  time
 
def sayHi(n):
     time.sleep( 1 )
     print  'Hi this is thread %s'  %n
 
thread_list = []    #用来存放多线程执行返回的函数入口,因此这里存放的是函数入口
 
for  in  range( 20 ):
     thread_list.append(threading.Thread(target=sayHi, args=(i,)))
 
for  in  thread_list:    #执行列表中存放的函数入口,只有执行了之后才会执行sayHi()的程序代码,否则上面只是把函数入口存放在这个列表中而已
     i.start()
 
for  in  thread_list:    #检测对应的线程是否已经执行完毕(即函数入口是否已经被执行,从而执行相关的程序代码)
     i.join()    #join()中可以加超时时间,如i.join( 3 ),表示当前i对应的函数入口所执行的
     线程,如果在 3 秒内还没有执行完就超时,在线程可以正常执行的时候不加也是没有关系的,
     但是当线程出现异常而无法正常执行时,由于i.join()还没有检测到线程已经执行完毕,所
     以会一直处于等待状态,这样的话就会造成程序的代码不能继续执行(程序还停留在i.join(
     )这里等待这一个其对应的线程执行完毕),设定超时时间就可以避免这一个问题,下面会有相关说明
 
print  '\033[32;1mThis is the last line\033[0m'

    程序执行结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day7$ python day6thread1.py 
Hi  this  is  thread  0
Hi  this  is  thread  1
Hi  this  is  thread  2
Hi  this  is  thread  3
Hi  this  is  thread  4
Hi  this  is  thread  5
Hi  this  is  thread  6
Hi  this  is  thread  7
Hi  this  is  thread  8
Hi  this  is  thread  9
  Hi  this  is  thread  11
  Hi  this  is  thread  14
  Hi  this  is  thread  17
  Hi  this  is  thread  12
Hi  this  is  thread  15
Hi  this  is  thread  16
Hi  this  is  thread  10
Hi  this  is  thread  13
Hi  this  is  thread  18
Hi  this  is  thread  19
This  is  the last line

    将程序代码修改为如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
 
import  threading
import  time
 
def sayHi(n):
     time.sleep( 1 )
     print  'Hi this is thread %s'  %n
 
thread_list = []
 
for  in  range( 20 ):
     thread_list.append(threading.Thread(target=sayHi, args=(i,)))
 
for  in  thread_list:
     i.start()
 
# for  in  thread_list:
#   i.join()
 
print  '\033[32;1mThis is the last line\033[0m'

    程序执行结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day7$ python day6thread1.py 
This  is  the last line
Hi  this  is  thread  0
  Hi  this  is  thread  2
  Hi  this  is  thread  6
  Hi  this  is  thread  9
  Hi  this  is  thread  10
  Hi  this  is  thread  15
  Hi  this  is  thread  16
  Hi  this  is  thread  3
Hi  this  is  thread  8
Hi  this  is  thread  11
  Hi  this  is  thread  14
Hi  this  is  thread  17
Hi  this  is  thread  5
Hi  this  is  thread  13
Hi  this  is  thread  4
Hi  this  is  thread  1
Hi  this  is  thread  7
Hi  this  is  thread  12
Hi  this  is  thread  18
Hi  this  is  thread  19

    对比两个例子可以发现,不同之处在于“This is the last line”的输出位置,未修改代码前是在最后,而修改代码后则在最前,作如下解释:

第一个例子由于加了join()作检测,程序的代码会停在i.join()的代码块中,而这里又没有设置超时时间,因此会直到检测到所有的进程都执行完毕才开始执行该代码块后面的程序代码,因此,“This is the last line”会在最后面输出;

第二个例子没有加join()作检测,所以不管线程是否已经执行完毕,只要把所有函数入口加入线程中开始执行,就马上执行i.start()代码块后面的程序代码,由于多线程执行的函数加了sleep(1),所以线程执行的输出肯定比后面打印“This is the last line”要慢,因此,这一句会在最前面输出。

    多线程是这样,多进程也是类似的,前面已经有详细的例子和说明。


2.有关于join()的进一步解释说明

    其实在第一个例子的程序代码中已经给出了join()的解释说明,这里只需要再看下面一个例子就更加好理解了。

    程序代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
 
import  threading
import  time
 
def sayHi(n):
     time.sleep( 2 )
     print  'Hi this is thread %s'  %n
 
thread_list = []
 
for  in  range( 10 ):
     thread_list.append(threading.Thread(target=sayHi, args=(i,)))
 
for  in  thread_list:
     i.start()
 
for  in  thread_list:
     print i.join( 0.1 )
 
print  '\033[32;1mThis is the last line\033[0m'

    程序执行结果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
xpleaf@xpleaf-machine:/mnt/hgfs/Python/day7$ time python day6thread1.py 
None
None
None
None
None
None
None
None
None
None
This  is  the last line
Hi  this  is  thread  0
Hi  this  is  thread  1
Hi  this  is  thread  2
Hi  this  is  thread  3
Hi  this  is  thread  4
Hi  this  is  thread  5
  Hi  this  is  thread  7
  Hi  this  is  thread  8
Hi  this  is  thread  6
Hi  this  is  thread  9
 
real    0m2.080s
user    0m0.048s
sys 0m0.016s

    作如下解释说明:

1)程序代码到了i.join()时,由于0.1秒超时,而线程执行函数sleep2秒;

2)0.1秒过去后,第一个线程超时,i.join()检测第二个线程,打印输出None;

3)0.1秒过去后,第二个线程超时,i.join()检测第三个线程,打印输出None;

……

4)检测完10个线程,用了1秒,此时join()的工作完成(总共输出了10个None),执行join()后面的代码块;

5)join()后面的代码块输出“This is the last line”;

6)再过1秒后,所有线程sleep完,总共输出10句“Hi this is thread ”;

7)程序执行完毕,进程结束。

    通过上面这一个例子的分析,相信无论是对多线程的执行过程,还是对join()函数的理解,都会有更进一步的认识。

相关文章
|
3月前
|
分布式计算 并行计算 安全
在Python Web开发中,Python的全局解释器锁(Global Interpreter Lock,简称GIL)是一个核心概念,它直接影响了Python程序在多线程环境下的执行效率和性能表现
【6月更文挑战第30天】Python的GIL是CPython中的全局锁,限制了多线程并行执行,尤其是在多核CPU上。GIL确保同一时间仅有一个线程执行Python字节码,导致CPU密集型任务时多线程无法充分利用多核,反而可能因上下文切换降低性能。然而,I/O密集型任务仍能受益于线程交替执行。为利用多核,开发者常选择多进程、异步IO或使用不受GIL限制的Python实现。在Web开发中,理解GIL对于优化并发性能至关重要。
52 0
|
13天前
|
API Python
探索Python中的多线程编程
探索Python中的多线程编程
35 5
|
23天前
|
调度 Python
Python 中如何实现多线程?
【8月更文挑战第29天】
40 6
|
26天前
|
API C语言 C++
C调用Python之多线程与traceback打印
C调用Python之多线程与traceback打印
26 2
|
1月前
|
数据采集 Java Python
Python并发编程:多线程(threading模块)
Python是一门强大的编程语言,提供了多种并发编程方式,其中多线程是非常重要的一种。本文将详细介绍Python的threading模块,包括其基本用法、线程同步、线程池等,最后附上一个综合详细的例子并输出运行结果。
|
30天前
|
数据采集 Java Python
Python并发编程:多线程(threading模块)
本文详细介绍了Python的threading模块,包括线程的创建、线程同步、线程池的使用,并通过多个示例展示了如何在实际项目中应用这些技术。通过学习这些内容,您应该能够熟练掌握Python中的多线程编程,提高编写并发程序的能力。 多线程编程可以显著提高程序的并发性能,但也带来了新的挑战和问题。在使用多线程时,需要注意避免死锁、限制共享资源的访问,并尽量使用线程池来管理和控制线程。
|
1月前
|
开发工具 计算机视觉 Python
大恒相机 - Python 多线程拍摄
大恒相机 - Python 多线程拍摄
34 1
|
1月前
|
调度 Python
|
1月前
|
Shell Python
Python多线程怎么做?
Python 3 中利用 `threading` 模块实现多线程。创建与执行线程有两种常见方式:一是直接使用 `Thread` 类实例,指定目标函数;二是通过继承 `Thread` 类并重写 `run` 方法。前者构造 `Thread` 对象时通过 `target` 参数指定函数,后者则在子类中定义线程的行为。两种方式均需调用 `start` 方法启动线程。示例展示了这两种创建线程的方法及输出顺序,体现线程并发执行的特点。
|
2月前
|
安全 Java 调度
「Python入门」Python多线程
1. **线程与进程区别**:线程共享内存,进程独立;线程启动快,多线程效率高于多进程。 2. **多线程使用**:直接使用Thread类,通过`target`指定函数,`args`传递参数;或继承Thread,重写`run`方法。 3. **守护线程**:设置`setDaemon(True)`,主线程结束时,守护线程一同结束。 4. **join线程同步**:主线程等待子线程完成,如`t.join()`。 5. **线程锁**(Mutex):防止数据竞争,确保同一时间只有一个线程访问共享资源。 6. **RLock(递归锁)**:允许多次锁定,用于需要多次加锁的递归操作。
27 1
「Python入门」Python多线程