python 簡單任務拆分多執行緒框架
阿新 • • 發佈:2019-01-07
#-*- encoding: gb2312 -*-
import string
import threading
import time
def thread_main(a):
global count, mutex
# 獲得執行緒名
threadname = threading.currentThread().getName()
for x in xrange(0, int(a)):
# 取得鎖
mutex.acquire()
count = count + 1
# 釋放鎖
mutex.release()
print threadname, x, count
time.sleep(1)
def main(num):
global count, mutex
threads = []
count = 1
# 建立一個鎖
mutex = threading.Lock()
# 先建立執行緒物件
for x in xrange(0, num):
threads.append(threading.Thread(target=thread_main, args=(10,)))
# 啟動所有執行緒
for t in threads:
t.start()
# 主執行緒中等待所有子執行緒退出
for t in threads:
t.join()
if __name__ == '__main__':
num = 4
# 建立4個執行緒
main(4)
import string
import threading
import time
def thread_main(a):
global count, mutex
# 獲得執行緒名
threadname = threading.currentThread().getName()
for x in xrange(0, int(a)):
# 取得鎖
mutex.acquire()
count = count + 1
# 釋放鎖
mutex.release()
print threadname, x, count
time.sleep(1)
def main(num):
global count, mutex
threads = []
count = 1
# 建立一個鎖
mutex = threading.Lock()
# 先建立執行緒物件
for x in xrange(0, num):
threads.append(threading.Thread(target=thread_main, args=(10,)))
# 啟動所有執行緒
for t in threads:
t.start()
# 主執行緒中等待所有子執行緒退出
for t in threads:
t.join()
if __name__ == '__main__':
num = 4
# 建立4個執行緒
main(4)