Python多线程编程
来源:互联网 发布:三维软件 编辑:程序博客网 时间:2024/06/05 00:24
使用线程有两种方法,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行。
# -*- coding: utf-8 -*-import threadingimport timeimport randomcount = 0mutex = threading.Lock()def thread_main(i): global count, mutex thread_name = threading.currentThread().getName() for x in xrange(0, int(i)): mutex.acquire() count += 1 print thread_name, x, count mutex.release() time.sleep(random.randint(1, 3))def main(num): global count, mutex threads = [] for x in xrange(0, num): threads.append(threading.Thread(target=thread_main, args=(3, ))) # loop 3 rounds for t in threads: t.start() for t in threads: t.join()if __name__ == '__main__': main(4) # create 4 threads
输出:
Thread-1 0 1Thread-2 0 2Thread-3 0 3Thread-4 0 4Thread-1 1 5Thread-2 1 6Thread-3 1 7Thread-4 1 8Thread-1 2 9Thread-4 2 10Thread-3 2 11Thread-2 2 12
第二种方法是直接从Thread继承,创建一个新的类,把线程执行的代码放到这个新类里。
# -*- coding: utf-8 -*-import threadingimport timeimport randomclass Test(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self.run_num = num def run(self): global count, mutex thread_name = threading.currentThread().getName() for x in xrange(0, int(self.run_num)): mutex.acquire() count += 1 print thread_name, x, count mutex.release() time.sleep(random.randint(1, 3))if __name__ == '__main__': global count, mutex threads = [] count = 0 mutex = threading.Lock() for t in xrange(0, 4): # create 4 threads threads.append(Test(3)) # loop 3 rounds for t in threads: t.start() for t in threads: t.join()
输出:
Thread-1 0 1Thread-2 0 2Thread-3 0 3Thread-4 0 4Thread-1 1 5Thread-2 1 6Thread-4 1 7Thread-3 1 8Thread-1 2 9Thread-2 2 10Thread-3 2 11Thread-4 2 12
0 0
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- zt:python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- Python多线程编程
- python 多线程编程
- python 多线程编程
- python sqlite多线程编程
- python 多线程编程
- python多线程编程
- python多线程编程
- python 多线程编程
- python多线程编程
- VMware下CentOS7网络重启出错解决方案
- Problem C. Evaluation Google APAC 2017 University Test Round C
- Android状态栏微技巧,带你真正理解沉浸式模式
- 【BZOJ】2657: [Zjoi2012]旅游(journey)
- 1036. 跟奥巴马一起编程(15)
- Python多线程编程
- FTP协议讲解
- 【笔试练习】美团笔试题(一)
- Android笔记->Executors应用学习
- 1037. 在霍格沃茨找零钱(20)
- 《招聘一个靠谱的iOS》面试题参考答案
- PLSQL Dynamic SQL one row result
- UVa 455 Periodic Strings 【字符串求周期】
- Python socket编程