Python多线程(2)
来源:互联网 发布:ubuntu卡在安装界面 编辑:程序博客网 时间:2024/05/18 10:09
写几个多线程的例子
在python的threading module里有如下一段话:Due to the Global Interpreter Lock, in CPython only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better of use of the computational resources of multi-core machines, you are advised to use multiprocess. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.
example1:
import threading
import time
import sys
import os
class myThrd(threading.Thread):
def run(self):
while True:
print "Thread: " + self.getName()
time.sleep(1)
def test():
while True:
print "Thread: test"
time.sleep(1)
if __name__=='__main__':
t1 = myThrd()
t2 = threading.Thread(target=test, args=(), name='test thread')
main = threading.currentThread()
print main.getName()
t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
t2.start()
t1.join()
t2.join()
exampel 2:
import Queue
import threading
import socket
import sys
import os
import time
def produce(queue):
while True:
queue.put(time.strftime('%X %x %Z'), False)
time.sleep(1)
def consume(queue):
while True:
print "Queue size: " + str(queue.qsize())
item = queue.get()
print str(item)
time.sleep(5)
queue = Queue.Queue(1000)
producer = threading.Thread(target=produce, args=(queue,))
consumer = threading.Thread(target=consume, args=(queue,))
producer.setDaemon(True)
producer.start()
consumer.start()
consumer.join()
- Python多线程(2)
- Python多线程下载(2)
- Python多线程2:sched
- Python 多线程2
- Python多线程
- Python多线程
- Python多线程
- python多线程
- python 多线程
- python多线程
- python多线程
- python 多线程
- python多线程
- Python多线程
- Python 多线程
- python多线程
- python 多线程
- {python多线程}
- [MW]第一篇
- 【初学设计模式】Composite (组合)
- linux根文件系统理解
- 【初学设计模式】Decorator (装饰)
- android 系统调用例子
- Python多线程(2)
- DTD文章
- 【初学设计模式】Facade (外观)
- 烧写2410-S linux 操作系统
- shell实例(十九) ---nl,bc命令
- 【初学设计模式】Flyweight (享元)
- Virtual Shard
- 用java代码实现native2ascii的功能
- Android资源管理——资源文件的创建、读取和管理