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()