使用并行线程在python中进行多线程处理

时间:2015-01-22 11:50:10

标签: python multithreading

我创建了两个运行不同功能的线程。 我试图实现的是,如果第一个线程结束,那么第二个线程也应该结束(我尝试使用全局变量实现它) 一旦两个线程结束相同的过程应该继续。 该脚本未按预期工作。

我正在使用Linux - Centos和python 2.7

#!/usr/bin/python

import threading
import time
import subprocess
import datetime
import os
import thread


command= "strace -o /root/Desktop/a.txt -c ./server"
final_dir = "/root/Desktop/"
exitflag = 0
# Define a function for the thread
def print_time(*args):
    os.chdir(final_dir)
    print "IN first thread"
    proc = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.wait(70)
    exitflag=1

def print_time1(*args):
    print "In second thread"
    global exitflag
    while exitflag:
        thread.exit()
        #proc = subprocess.Popen(command1,shell=True,stdout=subprocess.PIPE, sterr=subprocess.PIPE)



# Create two threads as follows

    while (1):
        t1=threading.Thread(target=print_time)
        t1.start()
        t2=threading.Thread(target=print_time1)
        t2=start()
        time.sleep(80)
        z = t1.isAlive()
        z1 = t2.isAlive()
        if z:
            z.exit()
        if z1:
            z1.exit()
        threading.Thread(target=print_time1).start()
        threading.Thread(target=print_time1).start()
        print "In try"

我哪里错了?

2 个答案:

答案 0 :(得分:1)

您可以创建一个共享状态的对象,并让依赖线程检查该状态。类似的东西:

import threading
import time
import datetime

class Worker1( threading.Thread ):
    def __init__(self, state):
        super(Worker1, self).__init__()
        self.state = state    

        def run(self):
            print_time_helper("Worker1 Start")
        time.sleep(4)
        print_time_helper("Worker1 End")
        self.state.keepOnRunning = False

class Worker2( threading.Thread ):
    def __init__(self, state):
        super(Worker2, self).__init__()
        self.state = state 

    def run(self):
        while self.state.keepOnRunning:
            print_time_helper("Worker2")
            time.sleep(1)

class State( object ):
    def __init__(self):
        self.keepOnRunning = True        

def main():
    state = State()

    thread1 = Worker1(state)
    thread2 = Worker2(state)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

def print_time_helper(name):
    print "{0}: {1}".format(name, datetime.datetime.now().time().strftime("%S"))

将输出类似的内容(数字显示当前时间秒):

Worker1 Start: 39
Worker2: 39
Worker2: 40
Worker2: 41
Worker2: 42
Worker1 End: 43

然而,对于大多数情况来说,这有点简单。你可能最好使用消息队列 - this是一个很好的介绍。

答案 1 :(得分:0)

使用threading.Event而不是int并等待它被设置。

此外,你的逻辑在print_time1中似乎是错误的,因为你的while循环永远不会运行,因为exitflag最初是0,但即使它是1,它仍然会立即退出。它实际上并没有等待任何事情。

相关问题