[TOC]
### threading.Thread類
Thread是對thread模塊的封裝,開啟的子線程默認是非守護線程,不會隨主線程一切結束。
#### 常用方法
```
start() #開始執行該線程
join(timeout=None) #子線程join到主線程
setName(name) --> thread.name
getName() #取得線程名
is_alive()/isAlive() #線程是否存活的標志
setDaemon(False) --> thread.daemon = False
isDaemon()
activeCount()/active_count() # 當前活動對象個數
currentThread()/current_thread() # 返回當前Thread對象
enumerate() # 返回Thread對象列表
```
#### threading.Thread的初始化函數
```
def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
```

### 直接調用線程
`join`命名來源于posix標準。子線程join到主線程(啟動程序的線程,比如c語言執行main函數的線程)。你的問題可能在于沒有理解join,阻塞線程僅僅是一個表現,而非目的。其目的是等待當前線程執行完畢后,”計算單元”與主線程匯合。
```
#!/usr/bin/env python
# coding: utf-8
import threading
from time import ctime,sleep
def music(func):
for i in range(5):
print "I was listening to %s. %s" %(func,ctime())
sleep(1)
def move(func):
for i in range(1):
print "I was at the %s! %s" %(func,ctime())
sleep(2)
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()
# 等待線程結束,與主線程會和,這兩個線程都阻塞,主線程不會往下執行。
for t in threads:
t.join()
print "all over %s" %ctime()
```
### 自定義線程類
```
#!/usr/bin/python
# coding: UTF-8
import threading
import time
class myThread(threading.Thread): #繼承父類threading.Thread
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self): #把要執行的代碼寫到run函數里面 線程在創建后會直接運行run函數
print "Starting " + self.name
printTime(self.name, self.counter)
print "Exiting " + self.name
def printTime(threadName, counter):
for i in xrange(counter):
time.sleep(1)
print "%s: %s" % (threadName, time.ctime(time.time()))
# 創建新線程
thread1 = myThread(1, "Thread-1", 3)
thread2 = myThread(2, "Thread-2", 5)
# 開啟線程
thread1.start()
thread2.start()
print "Exiting Main Thread"
```
#### 線程池
使用信號量充當線程池
下面的做法同樣會造成資源競爭,應該將信號量參數改為1
```
#!/usr/bin/env python
# coding: utf-8
import time
from threading import Thread, Lock, BoundedSemaphore
num = 0
def add():
time.sleep(1)
with lock:
global num
num += 1
print num
lock = BoundedSemaphore(1000)
for i in range(10000):
add_thread = Thread(target=add, args=())
add_thread.start()
```
- 前言
- 環境搭建
- 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