python 多线程 start_new_thread()
2015-04-22 15:00
405 查看
一、简述
CPython实现细节: 由于GIL(Global Interpreter Lock),在CPython中一次只能有一个线程来执行python代码,不过有些面向执行的库可以克服这个限制。如果想要使你的应用程序更好的利用计算机资源的话,最好使用multiprocessing。 但是,如果同时运行多个I/O任务的话,线程依然是一个很好地选择。python线程的作用主要是应对I/O任务,例如网络数据的读写等。
二、示例
1. 函数说明。start_new_thread ( function , args [ , kwargs ] )
创建一个新的线程,返回一个线程标识符。function是线程函数,args是线程函数的参数,是一个list。kwargs可选参数,可不填。
#!/usr/bin/env python # _*_ coding = utf-8 _*_ import thread import time def work_thread(id): cnt = 1 print "Thread %d is runing..." % id while True: print "Thread with ID %d has counter value %d" % (id, cnt) time.sleep(2) cnt += 1 for i in range(1,5): thread.start_new_thread(work_thread,(i,)) print "Main thread doing an infinite wait loop..." while True: pass
运行代码,输出结果如下:
$ ./thread_demo.py
Main thread doing an infinite wait loop…
Thread 3 is runing…
Thread 1 is runing…
Thread 2 is runing…
Thread 4 is runing…
Thread with ID 1 has counter value 1
Thread with ID 4 has counter value 1
Thread with ID 2 has counter value 1
Thread with ID 3 has counter value 1
Thread with ID 2 has counter value 2
Thread with ID 3 has counter value 2
Thread with ID 4 has counter value 2
Thread with ID 1 has counter value 2
Thread with ID 3 has counter value 3
Thread with ID 4 has counter value 3
Thread with ID 1 has counter value 3
Thread with ID 2 has counter value 3
Thread with ID 1 has counter value 4
Thread with ID 4 has counter value 4
Thread with ID 2 has counter value 4
Thread with ID 3 has counter value 4
线程退出函数:
thread.exit ()。结束当前线程。调用该函数会触发 SystemExit 异常,如果没有处理该异常,线程将结束。
相关文章推荐
- 多线程中有无new ThreadStart()的区别
- C# 多线程,new ThreadStart(方法)中的方法如果有参数,该怎么写
- C# 多线程编程 ThreadStart ParameterizedThreadStart
- python的多线程编程 --- thread模块
- JAVA多线程之——Thread中start()和run()的区别
- runnable和thread的区别以及run和start的区别(多线程)
- Python多线程thread与threading实现
- Java多线程系列--“基础篇”03之 Thread中start()和run()的区别
- python多线程编程之thread模块
- python--thread多线程总结
- python3 多线程 threading _thread
- 以ThreadStart方式实现多线程
- JAVA多线程之——Thread中start()和run()的区别
- Java多线程系列--“基础篇”03之 Thread中start()和run()的区别
- Static block start new thread
- Python学习笔记--多线程编程,thread
- Java多线程系列--“基础篇”03之 Thread中start()和run()的区别
- Java多线程之Thread的run()与start()方法解析
- ThreadStart方式实现多线程
- ASP.NET温故而知新学习系列之ASP.NET多线程编程—.NET下的多线程编程利用thread.Start()传递参数(四)