1

I have created a threading class however and call start and join on them, however when I run the Thread.isAlive() all of them, come back as False. I am not sure if I have set up my threading class correctly, I tried to follow this post How to use threading in Python? Michael Safyan's answer.

Here is my Thread class

class Thread(threading.Thread):
def __init__(self, host, communityString, deviceID, script):
    super(Thread, self).__init__()
    self.host = host
    self.communityString=communityString
    self.deviceID = deviceID
    self.script=script

def CreateScript(self):
#ScriptsToGenerate = GetDatasourceScripts(deviceID)
    print self.script['scriptType']
    #We check if script type is SNMP and if it is we will add the oids that matter into the SNMP script
    if self.script['scriptType'] == "SNMP":
        print self.script['parentOID']
        #walk the parent node to see if these exist
        oidsToInputInScript = SNMPWalkChildren(self.host, self.communityString, self.script['OID'])
        print oidsToInputInScript
        if oidsToInputInScript != "":
            self.script['script'].replace("[oid]", oidsToInputInScript)

    SaveScript(self.host, self.script['timeInterval'], self.script)


def SaveScript(name, Interval, script):
    createFolder = ""

    for root, dirs, files in os.walk("/home/pi/", topdown=False):
        for name in dirs:
            if name == "myDir":
                createFolder = os.path.join(root, name)
                print createFolder

    absPath = createFolder + "/" + Interval
    print absPath
    if not os.path.exists(absPath):
        os.system("sudo mkdir " + absPath)
        os.chmod(absPath, stat.S_IRWXO | stat.S_IRWXU | stat.S_IRWXG)

    scriptName = name.replace(".", "")

    #create script file and save it in that location
    #need to replace "name" with a distinguishable name
    saveFile = absPath + "/" + scriptName + "_" + script["dsID"] + "_" + script["dpID"] + ".py"
    print saveFile
    with open(saveFile, "w") as script_file:
        os.chmod(saveFile, stat.S_IRWXO | stat.S_IRWXU | stat.S_IRWXG)
        script_file.write(script["text"])


def SNMPWalkChildren(host, communityString, OID):
    result = ""
    try:
        cmdGen = cmdgen.CommandGenerator()

        errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
            cmdgen.CommunityData(communityString),
            cmdgen.UdpTransportTarget((host, 161)),
            parentOID
        )

        if errorIndication:
            print(errorIndication)
        else:
            if errorStatus:
                print('%s at %s' % (
                    errorStatus.prettyPrint(),
                    errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
                    )
                )
            else:
                for varBindTableRow in varBindTable:
                    for name, val in varBindTableRow:
                        print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))
                        result += "\"" + str(name) + "\"" + ', '
                return result[:-2]
    finally:
        return result

and here is where I call start on the thread

threadList = list() 
#Loop through and create threads for each script
for scripts in ds:
    thread = Thread(name, communityString, deviceID, scripts)
    threadList.append(thread)
    print "Thread has started"
    print scripts
    thread.start()
    thread.join()

for threads in threadList:
    print(threads.isAlive())
Community
  • 1
  • 1
Johnathon64
  • 1,280
  • 1
  • 20
  • 45

1 Answers1

3

You join each thread as it is started; that means it must complete before the loop continues. So by the time you get to the second for loop, all the threads have completed, so none of them are still alive.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • So does that mean that they haven't executed the code within the thread? – Johnathon64 Aug 11 '15 at 13:26
  • No, on the contrary, it means they *have*, but they each execute in sequence; you start a thread then join it - which means waiting until it finishes executing - and only then start the next new thread. In other words, there's no benefit to using threads here at all. – Daniel Roseman Aug 11 '15 at 13:29
  • so I should start the threads in a for loop and join them after they have all started? – Johnathon64 Aug 11 '15 at 13:32
  • Also I have a couple of print statements within the thread class, however I cannot see them being printed at all. – Johnathon64 Aug 11 '15 at 13:36
  • 1
    excuse my ignorance: I do not see any `run` method being overridden nor any `target` parameter being passed to `Thread`. How/what should be started then? – Pynchia Aug 11 '15 at 13:38