python 中的多线程使用并行线程

Multi threading in python using parallel threads

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

我正在使用 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"

我哪里错了?

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

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 是一个很好的介绍。

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

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