Skip to content

Files

Latest commit

ae68a0c · Nov 20, 2019

History

History
97 lines (64 loc) · 2.25 KB

32.md

File metadata and controls

97 lines (64 loc) · 2.25 KB

threading_thread

原文: https://pythonspot.com/threading

在 Python 中,您可以使用 Python 2.x 中的threading模块或 Python 3 中的_thread模块创建线程。我们将使用threading模块与之交互。

线程是一种操作系统进程,具有与正常进程不同的功能:

  • 线程作为进程的子集存在
  • 线程共享内存和资源
  • 进程具有不同的地址空间(在内存中)

什么时候使用线程处理? 通常,当您希望功能与程序同时出现时。 如果创建服务器软件,则希望服务器不仅侦听一个连接,而且侦听许多连接。 简而言之,线程使程序能够一次执行多个任务。

Python 线程

让我们创建一个线程程序。 在此程序中,我们将启动 10 个线程,每个线程将输出其 ID。

import threading

# Our thread class
class MyThread (threading.Thread):

    def __init__(self,x):
        self.__x = x
        threading.Thread.__init__(self)

    def run (self):
          print str(self.__x)

# Start 10 threads.
for x in xrange(10):
    MyThread(x).start()

输出:

0
1
...
9

如果运行一次,线程不必停止。 线程可以是定时的,每x秒重复执行一次线程功能。

定时线程

在 Python 中,Timer类是Thread类的子类。 这意味着它的行为类似。我们可以使用计时器类来创建定时线程。计时器是通过.start()方法调用启动的,就像常规线程一样。 下面的程序创建一个线程,该线程在 5 秒钟后启动。

#!/usr/bin/env python
from threading import *

def hello():
    print "hello, world"

# create thread
t = Timer(10.0, hello)

# start thread after 10 seconds
t.start()

使用线程

重复执行功能我们可以像这样无休止地执行线程:

#!/usr/bin/env python
from threading import *
import time

def handleClient1():
    while(True):
        print "Waiting for client 1..."
        time.sleep(5) # wait 5 seconds      

def handleClient2():
    while(True):
        print "Waiting for client 2..."
        time.sleep(5) # wait 5 seconds

# create threads
t = Timer(5.0, handleClient1)
t2 = Timer(3.0, handleClient2)

# start threads
t.start()
t2.start()