使用连接在python中使用Class和不使用类进行多线程处理

时间:2014-11-18 11:11:03

标签: python multithreading python-2.7 join

我正在为我的项目练习python多线程环境。我已经开发了(可能复制:))一个示例程序,它将使用线程连接方法,因此主线程将等待其他线程完成,使用线程模型。

import threading
import time


class MyThread (threading.Thread):
    def __init__(self, thread_id, name, counter):
        threading.Thread.__init__(self)
        self.threadID = thread_id
        self.name = name
        self.counter = counter

    def run(self):
        print "Starting " + self.name
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # Free lock to release next thread
        threadLock.release()


def print_time(thread_name, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" % (thread_name, time.ctime(time.time()))
        counter -= 1

threadLock = threading.Lock()

thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)

thread1.start()
thread2.start()

print 'waiting to finish the thread'

thread1.join()
thread2.join()

print "Exiting Main Thread"

以上输出:

Starting Thread-1
waiting to finish the threadStarting Thread-2

Thread-1: Tue Nov 18 16:31:04 2014
Thread-1: Tue Nov 18 16:31:05 2014
Thread-1: Tue Nov 18 16:31:06 2014
Thread-2: Tue Nov 18 16:31:08 2014
Thread-2: Tue Nov 18 16:31:10 2014
Thread-2: Tue Nov 18 16:31:12 2014
Exiting Main Thread

Process finished with exit code 0

当我评论这些连接方法

#thread1.join()
#thread2.join()

然后我得到输出

Starting Thread-1
waiting to finish the threadStarting Thread-2

Exiting Main Thread
Thread-1: Tue Nov 18 16:32:31 2014
Thread-1: Tue Nov 18 16:32:32 2014
Thread-1: Tue Nov 18 16:32:33 2014
Thread-2: Tue Nov 18 16:32:35 2014
Thread-2: Tue Nov 18 16:32:37 2014
Thread-2: Tue Nov 18 16:32:39 2014

Process finished with exit code 0

预期

现在我又写了一个代码

import time
import threading


def printer():
    for _ in range(5):
        print 'Hello'
        time.sleep(1)

thread1 = threading.Thread(target=printer())
thread2 = threading.Thread(target=printer())
thread3 = threading.Thread(target=printer())
thread1.start()
thread2.start()
thread3.start()
print 'Bye Bye'

为此,我没有使用join()线程方法,但我得到的输出为

Hello
Hello
:
Hello
:
Hello
:
Hello
Bye Bye

Process finished with exit code 0

使用join()时,我的输出也相同。

根据我对线程和连接的理解,当我没有使用join()语句时,'Bye Bye'语句应该打印在某个地方的中间而不是最后一个。

在python中是否存在类和简单函数更改的行为?

1 个答案:

答案 0 :(得分:3)

target应该是一个函数,而不是函数的结果(除非该结果是函数)。例如。 target=printer。注意没有括号。

您实际执行的操作是printer三次。然后启动了三个无关的线程。然后打印再见。