Abhijatya Singh
Abhijatya Singh

Reputation: 642

Multi threading in python using parallel threads

I created two threads each running different functions. What i tryed to achieve is if first thread ends then the second should also end ( i tryed achieving it using global variable) Once both the threads end the same procedure should continue. The script is not working as expected.

I am using Linux - Centos and 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"

Where am i going wrong?

Upvotes: 1

Views: 159

Answers (2)

Dylan
Dylan

Reputation: 11

Use a threading.Event instead of an int and wait for it to be set.

Also your logic appears to be wrong in print_time1 because your while loop will never run since exitflag is initially 0, but even if it was 1 it would still just exit immediately. It's not actually waiting on anything.

Upvotes: 0

jlb83
jlb83

Reputation: 2178

You could create an object to share state, and have the dependent thread check that state. Something like:

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"))

which will output something like this (numbers show current time seconds):

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

However, this is a bit simplistic for most situations. You might be better off using message queues - this is a good intro.

Upvotes: 1

Related Questions