Last active
June 8, 2016 13:58
-
-
Save finghine/4494d56f6a2e7327cb4be2dd4614e5a4 to your computer and use it in GitHub Desktop.
python multihread example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#encoding:utf-8 | |
# multithread | |
import threading | |
import Queue | |
import time | |
# 实现initQuenue | |
# 实现testfun | |
# 修改线程数 | |
MAX_QUEUE_SIZE = 10001 | |
MAXTHREAD = 100 | |
TEST_QUEUE_SIZE = 10001 | |
g_queuelock = threading.Lock() | |
g_printlock = threading.Lock() | |
g_wrokQueue = Queue.Queue(MAX_QUEUE_SIZE) | |
g_exit_flag=False | |
def synPrint(message): | |
g_printlock.acquire() | |
print message | |
g_printlock.release() | |
def getQueueItem(): | |
g_queuelock.acquire() | |
isempty = False | |
item = "" | |
if g_wrokQueue.empty(): | |
isempty =True | |
else: | |
item = g_wrokQueue.get() | |
g_queuelock.release() | |
return isempty,item | |
class MainThread(threading.Thread): | |
def __init__(self,targetfunction): | |
threading.Thread.__init__(self) | |
self.tfunction = targetfunction | |
def run(self): | |
while not g_exit_flag: | |
isempty,item = getQueueItem() | |
if not isempty: | |
try: | |
# synPrint(self.name+":"+item) | |
self.tfunction(self.name,item) | |
except Exception, e: | |
print str(e) | |
def initQueue(): | |
global g_wrokQueue | |
# f = open("example.txt",'rb') | |
# for lines in f.readlines(): | |
# g_wrokQueue.put(liens) | |
# f.close() | |
for i in range(TEST_QUEUE_SIZE): | |
g_wrokQueue.put(str(i)) | |
def testfcun(threadname,item): | |
synPrint(threadname+":"+item) | |
def startThreads(): | |
global g_exit_flag | |
initQueue() | |
th = [MainThread(testfcun) for _ in range(MAXTHREAD)] | |
for i in th: | |
i.start() | |
while not g_wrokQueue.empty(): | |
time.sleep(1) | |
g_exit_flag = True | |
for i in th: | |
i.join() | |
def main(): | |
global g_exit_flag | |
g_exit_flag=False | |
startThreads() | |
synPrint("over") | |
main() | |
# need modify |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment