[TOC]
## thread模塊 較底層次線程模塊
使用thread模塊開啟的線程,會隨主線程`一起結束`;為了讓子線程能夠執行完任務,所以可以讓主線程睡眠或者給主線程加鎖,等待子線程結束后再釋放鎖。
```python
#!/usr/bin/env python
#coding: utf-8
#python2
"""為了不讓主進程執行完就退出,給主線程加鎖,當子線程執行結束后,釋放主線程的鎖
存在的問題:
當兩個線程執行次數不一致時,先結束的線程即會釋放主線程的鎖,導致未執行完的線程被迫退出
"""
import thread
import time
def processor(thread_name, times):
for i in range(times):
print i, thread_name
time.sleep(0.001)
# for循環結束,釋放鎖
lock.release()
lock = thread.allocate_lock()
lock.acquire()
thread.start_new_thread(processor, ('image', 5))
thread.start_new_thread(processor, ('sound', 3))
while lock.locked():
pass
```
### 當線程間的執行需要一定次序時,則需要給子線程也加鎖。
當主線程,hello線程和world線程,執行到需要獲取鎖的時候,如果獲取不到鎖,則阻塞在那里;world線程在獲取鎖 world_thread_lock的時候阻塞了,當hello線程釋放了 鎖world_thread_lock,輸出了‘world’;此時hello線程也在獲取鎖過程中阻塞了,所以當world線程釋放了hello_thread_lock,輸出了hello,這樣交替釋放彼此的鎖,實現了順序運行

```python
#!/usr/bin/env python
#coding: utf-8
#python2
import time
import thread
def hello():
for i in xrange(5):
hello_thread_lock.acquire()
print 'hello', time.time(),
world_thread_lock.release()
def world():
for i in xrange(5):
world_thread_lock.acquire()
print 'world', time.time()
hello_thread_lock.release()
time.sleep(1)
# 釋放主進程的鎖
main_thread_lock.release()
main_thread_lock = thread.allocate_lock()
main_thread_lock.acquire()
hello_thread_lock = thread.allocate_lock()
world_thread_lock = thread.allocate_lock()
world_thread_lock.acquire()
thread.start_new_thread(hello, ())
thread.start_new_thread(world, ())
while main_thread_lock.locked():
pass
```
```python
#!/usr/bin/env python
# coding: utf8
import thread
from time import sleep, ctime
loops = [4, 2]
def loop(nloop, nsec, lock):
print 'start loop', nloop, 'at:', ctime()
sleep(nsec)
print 'loop', nloop, 'done at:', ctime()
lock.release()
def main():
print 'starting threads...'
locks = []
loops_len = range(len(loops))
# 生成鎖列表
for i in loops_len:
lock = thread.allocate_lock()
lock.acquire()
locks.append(lock)
# 開啟進程
for i in loops_len:
thread.start_new_thread(loop, (i, loops[i], locks[i]))
# 等待所有的lock都釋放
for i in loops_len:
while locks[i].locked():
pass
print 'all DONE at:', ctime()
if __name__ == '__main__':
main()
```
- 前言
- 環境搭建
- pypi
- 打包
- Python 2 和 Python 3 的版本之間差別
- 項目
- 第一部分
- 第1章 基礎
- Python安裝
- python代碼文件類型
- python對象
- 核心數據類型
- 核心數據類型--整型和浮點型
- 核心數據類型--字符串
- str.format
- 核心數據類型--列表
- 核心數據類型--元組
- 核心數據類型--字典
- 核心數據類型--集合
- 核心數據類型--文件對象
- 調用bash
- 標準輸入輸出
- str-repr
- 字符編碼
- 迭代器和生成器
- 第2章 語句和語法
- 賦值語句
- if語句
- while語句
- for語句
- assert
- 第3章 函數
- 函數作用域
- 工廠函數
- 內置函數
- 遞歸
- 嵌套作用域和lambda
- 參數傳遞
- 函數式編程
- property可寫與可讀
- 第5章 模塊
- 模塊導入
- 模塊命名空間
- 相對導入和絕對導入
- 模塊重載
- 在模塊中隱藏數據
- 過渡性重載
- 第6章 類
- 面向對象還是面向過程?
- 構造函數 析構函數
- call
- 運算符重載
- str()
- 待定
- 即時生成屬性
- 多態
- 線程和進程
- thread模塊
- threading模塊
- threading線程鎖
- 糖果機
- multiprocessing
- 阻塞非阻塞同步異步
- 單線程和多線程對比
- 生產者消費者模型
- 第二部分
- 獲取系統資源信息
- 獲取進程所占的物理內存
- dmidecode獲取系統信息
- 網絡編程
- 網絡基礎
- python中的套接字
- socket模塊
- 第三部分 高級功能
- 閉包入門
- 閉包的應用
- 裝飾器入門
- 裝飾器應用
- 第四部分 項目實戰
- graphite
- 模塊
- collections
- datetime
- Enum
- faker
- fabric
- fileinput
- fire
- fnmatch
- getpass
- glob
- hashlib
- heapq
- json模塊
- log
- os
- Paramiko
- parser
- platform
- pyyaml
- Queue
- random
- re
- 特殊符號和字符
- re模塊
- shelves
- subprocess
- time
- urllib_urllib2_requests
- urllib urllib2
- requests
- 標準模塊ConfigParser
- 擴展模塊Mysqldb
- 擴展模塊dns
- 擴展模塊request
- uuid
- cacheout 緩存庫
- delorean 時間
- 附錄
- 內置函數
- python實現各種排序算法
- 常見報錯
- pymongo
- pyrocksdb
- 常用
- ERROR