|
1 | 1 | # 线程 |
2 | 2 |
|
| 3 | +**线程(thread)是进程(process)中的一个实体,一个进程至少包含一个线程**。比如,对于视频播放器,显示视频用一个线程,播放音频用另一个线程。如果我们把进程看成一个容器,则线程是此容器的工作单位。 |
| 4 | + |
| 5 | +进程和线程的区别主要有: |
| 6 | + |
| 7 | +- 进程之间是相互独立的,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,但互不影响;而同一个进程的多个线程是内存共享的,所有变量都由所有线程共享; |
| 8 | +- 由于进程间是独立的,因此一个进程的崩溃不会影响到其他进程;而线程是包含在进程之内的,线程的崩溃就会引发进程的崩溃,继而导致同一进程内的其他线程也奔溃; |
| 9 | + |
| 10 | +# 多线程 |
| 11 | + |
| 12 | +在 Python 中,进行多线程编程的模块有两个:thread 和 threading。其中,thread 是低级模块,threading 是高级模块,对 thread 进行了封装,一般来说,我们只需使用 threading 这个模块。 |
| 13 | + |
| 14 | +下面,我们看一个简单的例子: |
| 15 | + |
| 16 | +```python |
| 17 | +from threading import Thread, current_thread |
| 18 | + |
| 19 | +def thread_test(name): |
| 20 | + print 'thread %s is running...' % current_thread().name |
| 21 | + print 'hello', name |
| 22 | + print 'thread %s ended.' % current_thread().name |
| 23 | + |
| 24 | +if __name__ == "__main__": |
| 25 | + print 'thread %s is running...' % current_thread().name |
| 26 | + print 'hello world!' |
| 27 | + t = Thread(target=thread_test, args=("test",), name="TestThread") |
| 28 | + t.start() |
| 29 | + t.join() |
| 30 | + print 'thread %s ended.' % current_thread().name |
| 31 | +``` |
| 32 | + |
| 33 | +可以看到,创建一个新的线程,就是把一个函数和函数参数传给 Thread 实例,然后调用 start 方法开始执行。代码中的 current_thread 用于返回当前线程的实例。 |
| 34 | + |
| 35 | +执行结果如下: |
| 36 | + |
| 37 | +``` |
| 38 | +thread MainThread is running... |
| 39 | +hello world! |
| 40 | +thread TestThread is running... |
| 41 | +hello test |
| 42 | +thread TestThread ended. |
| 43 | +thread MainThread ended. |
| 44 | +``` |
| 45 | + |
| 46 | +# 锁 |
| 47 | + |
| 48 | +由于同一个进程之间的线程是内存共享的,所以当多个线程对同一个变量进行修改的时候,就会得到意想不到的结果。 |
| 49 | + |
| 50 | +让我们先看一个简单的例子: |
| 51 | + |
| 52 | +```python |
| 53 | +from threading import Thread, current_thread |
| 54 | + |
| 55 | +num = 0 |
| 56 | + |
| 57 | +def calc(): |
| 58 | + global num |
| 59 | + print 'thread %s is running...' % current_thread().name |
| 60 | + for _ in xrange(10000): |
| 61 | + num += 1 |
| 62 | + print 'thread %s ended.' % current_thread().name |
| 63 | + |
| 64 | +if __name__ == '__main__': |
| 65 | + print 'thread %s is running...' % current_thread().name |
| 66 | + |
| 67 | + threads = [] |
| 68 | + for i in range(5): |
| 69 | + threads.append(Thread(target=calc)) |
| 70 | + threads[i].start() |
| 71 | + for i in range(5): |
| 72 | + threads[i].join() |
| 73 | + |
| 74 | + print 'global num: %d' % num |
| 75 | + print 'thread %s ended.' % current_thread().name |
| 76 | +``` |
| 77 | + |
| 78 | +在上面的代码中,我们创建了 5 个线程,每个线程对全局变量 num 进行 10000 次的 加 1 操作,这里之所以要循环 10000 次,是为了延长单个线程的执行时间,使线程执行时能出现中断切换的情况。现在问题来了,当这 5 个线程执行完毕时,全局变量的值是多少呢?是 50000 吗? |
| 79 | + |
| 80 | +让我们看下执行结果: |
| 81 | + |
| 82 | +```python |
| 83 | +thread MainThread is running... |
| 84 | +thread Thread-34 is running... |
| 85 | +thread Thread-34 ended. |
| 86 | +thread Thread-35 is running... |
| 87 | +thread Thread-36 is running... |
| 88 | +thread Thread-37 is running... |
| 89 | +thread Thread-38 is running... |
| 90 | +thread Thread-35 ended. |
| 91 | +thread Thread-38 ended. |
| 92 | +thread Thread-36 ended. |
| 93 | +thread Thread-37 ended. |
| 94 | +global num: 30668 |
| 95 | +thread MainThread ended. |
| 96 | +``` |
| 97 | + |
| 98 | +我们发现 num 的值是 30668,事实上,num 的值是不确定的,你再运行一遍,会发现结果变了。 |
| 99 | + |
| 100 | +原因是因为 `num += 1` 不是一个原子操作,也就是说它在执行时被分成若干步: |
| 101 | + |
| 102 | +- 计算 num + 1,存入临时变量 tmp 中; |
| 103 | +- 将 tmp 的值赋给 num. |
| 104 | + |
| 105 | +由于线程是交替运行的,线程在执行时可能中断,就会导致其他线程读到一个脏值。 |
| 106 | + |
| 107 | +为了保证计算的准确性,我们就需要给 `num += 1` 这个操作加上`锁`。当某个线程开始执行这个操作时,由于该线程获得了锁,因此其他线程不能同时执行该操作,只能等待,直到锁被释放,这样就可以避免修改的冲突。创建一个锁可以通过 `threading.Lock()` 来实现,代码如下: |
| 108 | + |
| 109 | +```python |
| 110 | +from threading import Thread, current_thread, Lock |
| 111 | + |
| 112 | +num = 0 |
| 113 | +lock = Lock() |
| 114 | + |
| 115 | +def calc(): |
| 116 | + global num |
| 117 | + print 'thread %s is running...' % current_thread().name |
| 118 | + for _ in xrange(10000): |
| 119 | + lock.acquire() # 获取锁 |
| 120 | + num += 1 |
| 121 | + lock.release() # 释放锁 |
| 122 | + print 'thread %s ended.' % current_thread().name |
| 123 | + |
| 124 | +if __name__ == '__main__': |
| 125 | + print 'thread %s is running...' % current_thread().name |
| 126 | + |
| 127 | + threads = [] |
| 128 | + for i in range(5): |
| 129 | + threads.append(Thread(target=calc)) |
| 130 | + threads[i].start() |
| 131 | + for i in range(5): |
| 132 | + threads[i].join() |
| 133 | + |
| 134 | + print 'global num: %d' % num |
| 135 | + print 'thread %s ended.' % current_thread().name |
| 136 | +``` |
| 137 | + |
| 138 | +让我们看下执行结果: |
| 139 | + |
| 140 | +```python |
| 141 | +thread MainThread is running... |
| 142 | +thread Thread-44 is running... |
| 143 | +thread Thread-45 is running... |
| 144 | +thread Thread-46 is running... |
| 145 | +thread Thread-47 is running... |
| 146 | +thread Thread-48 is running... |
| 147 | +thread Thread-45 ended. |
| 148 | +thread Thread-47 ended. |
| 149 | +thread Thread-48 ended. |
| 150 | +thread Thread-46 ended. |
| 151 | +thread Thread-44 ended. |
| 152 | +global num: 50000 |
| 153 | +thread MainThread ended. |
| 154 | +``` |
| 155 | + |
| 156 | +## GIL 锁 |
| 157 | + |
| 158 | +讲到 Python 中的多线程,就不得不面对 `GIL` 锁,`GIL` 锁的存在导致 Python 不能有效地使用多线程实现多核任务,因为在同一时间,只能有一个线程在运行。 |
| 159 | + |
| 160 | +`GIL` 全称是 Global Interpreter Lock,译为**全局解释锁**。早期的 Python 为了支持多线程,引入了 GIL 锁,用于解决多线程之间数据共享和同步的问题。但这种实现方式后来被发现是非常低效的,当大家试图去除 GIL 的时候,却发现大量库代码已重度依赖 GIL,由于各种各样的历史原因,GIL 锁就一直保留到现在。 |
| 161 | + |
| 162 | +# 小结 |
| 163 | + |
| 164 | +- 一个程序至少有一个进程,一个进程至少有一个线程。 |
| 165 | +- 进程是操作系统**分配资源**(比如内存)的最基本单元,线程是操作系统能够进行**调度和分派**的最基本单元。 |
| 166 | +- 在 Python 中,进行多线程编程的模块有两个:thread 和 threading。其中,thread 是低级模块,threading 是高级模块,对 thread 进行了封装,一般来说,我们只需使用 threading 这个模块。 |
| 167 | +- 在执行多线程操作时,注意加锁。 |
| 168 | + |
| 169 | +# 参考资料 |
| 170 | + |
| 171 | +- [多线程 - 廖雪峰的官方网站](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143192823818768cd506abbc94eb5916192364506fa5d000) |
| 172 | +- [Python的GIL是什么鬼,多线程性能究竟如何 • cenalulu's Tech Blog](http://cenalulu.github.io/python/gil-in-python/) |
| 173 | +- [python中多进程以及多线程编程的总结 - Codefly](http://sunms.codefly.top/2016/11/05/python%E4%B8%AD%E5%A4%9A%E8%BF%9B%E7%A8%8B%E4%BB%A5%E5%8F%8A%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%BC%96%E7%A8%8B%E7%9A%84%E6%80%BB%E7%BB%93/) |
| 174 | + |
| 175 | + |
0 commit comments