首页 > 代码库 > 指定Python线程数目
指定Python线程数目
可以通过threading.semaphore()来指定并行运行的Python线程的数目。
#!/usr/bin/python2.7#File: threadsNum.py#Author: lxw#Time: 2014-09-07#Usage: Demonstration for control the number of threads.import threadingfrom myThread import MyThreadfrom time import sleepdef fib(x): sleep(0.005) if x < 2: return 1 return fib(x-2) + fib(x-1)argList = [13, 11, 15, 12, 14]def main(): #Limit the number of threads to 3. threadingNum = threading.Semaphore(3) threads = [] for arg in argList: t = MyThread(fib, (arg,), threadingNum, fib.__name__+str(arg)) threads.append(t) #There are 5 threads in all, but at most 3 of them run at the same time. for thread in threads: thread.start() for thread in threads: #if t is threading.currentThread(): # continue thread.join() print(thread.getResult())if __name__ == ‘__main__‘: main()else: print(‘Being imported as a module.‘)
其中用到的myThread.py如下:
#!/usr/bin/python2.7#File: myThread.py#Author: lxw#Time: 2014-09-06import threadingfrom time import ctimeclass MyThread(threading.Thread): def __init__(self, func, args, num, name=""): #if the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. threading.Thread.__init__(self) self.func = func self.args = args self.threadingNum = num self.name = name def getResult(self): return self.res def run(self): #NOTE: "with". with self.threadingNum: print("start {0} at: {1}".format(self.name, ctime())) self.res = apply(self.func, self.args) print("end {0} at: {1}".format(self.name, ctime()))
Output:
lxw@lxw-PC:TASK2$ python threadsNum.py start fib13 at: Sun Sep 7 16:11:23 2014start fib11 at: Sun Sep 7 16:11:23 2014start fib15 at: Sun Sep 7 16:11:23 2014end fib11 at: Sun Sep 7 16:11:24 2014start fib12 at: Sun Sep 7 16:11:24 2014end fib12 at: Sun Sep 7 16:11:26 2014start fib14 at: Sun Sep 7 16:11:26 2014end fib13 at: Sun Sep 7 16:11:26 2014377144end fib14 at: Sun Sep 7 16:11:33 2014end fib15 at: Sun Sep 7 16:11:33 2014987233610
Reference:
Python继承类的方式实现多线程及控制线程数: http://lihuipeng.blog.51cto.com/3064864/1322247
指定Python线程数目
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。