python 多线程

来源:互联网 发布:c语言语言 编辑:程序博客网 时间:2024/06/14 07:20

1.多线程的特点

    使用线程可以把占据长时间的程序中的任务放到后台去处理;


    用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度;


    程序的运行速度可能加快;


    在一些等待的任务实现上如用户输入、文件读写和网络收发数据等,线程就比较有用了。在这种情况下我们可以释放一些珍贵     的资源如内存占用等等。


   线程可以被抢占(中断)。


  在其他线程正在运行时,线程可以暂时搁置(也称为睡眠) -- 这就是线程的退让。


2.Python中使用线程

  函数式:调用thread模块中的start_new_thread()函数来产生新线程。

thread.start_new_thread ( function, args[, kwargs] )

其中

  • function - 线程函数。
  • args - 传递给线程函数的参数,他必须是个tuple类型。
  • kwargs - 可选参数。
Python通过两个标准库thread和threading提供对线程的支持。

thread 模块提供的其他方法:

  • threading.currentThread(): 返回当前的线程变量。
  • threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
  • threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

  • run(): 用以表示线程活动的方法。
  • start():启动线程活动。

  • join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
  • isAlive(): 返回线程是否活动的。
  • getName(): 返回线程名。
  • setName(): 设置线程名。
例  使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法:
#!/usr/bin/python# -*- coding: UTF-8 -*-import threadingimport timeexitFlag = 0class myThread (threading.Thread):      def __init__(self, threadID, name, counter):        threading.Thread.__init__(self)        self.threadID = threadID        self.name = name        self.counter = counter    def run(self):                          print ("Starting " + self.name)        print_time(self.name, self.counter, 5)        print ("Exiting " + self.name)def print_time(threadName, delay, counter):    while counter:        if exitFlag:            thread.exit()        time.sleep(delay)        print ("%s: %s" % (threadName, time.ctime(time.time())))        counter -= 1# 创建新线程thread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# 开启线程thread1.start()thread2.start()print ("Exiting Main Thread")
结果如下

0 0
原创粉丝点击