问题描述:

This code is to start and stop multiple copies of various different thread types. I will preface this with saying I tried using pipes to control the threads but keep getting random memory errors to do with the pipes. This is a prototype of a factory to produce several copies of multiple thread types, so a queue method didn't seem practical to me either though if there is something I am missing I am all ears. So my newest plan is to use a global dictionary with a different entry for every thread and thread kill condition. ie sub[Alive] subKill["kill"]

Yet for some reason the control_listener thread spawned by the processes wont trigger the kill condition and wont read the global variable.

from multiprocessing import Process, Pipe

from threading import Thread

import time

alive = {'subAlive': True, 'subKill': "Alive", 'testAlive': True, 'testKill': "Alive"};

def control_listener(aliveFlag, threadAlive): #listens for kill from main

global alive

while True:

data = alive[aliveFlag];

print "Thread", alive[threadAlive];

print "Thread status", alive[aliveFlag];

if data == "kill":

print "Killing"

alive[threadAlive] = False; #value for kill

print "testListner alive %s" % threadAlive, alive[threadAlive];

print "deactivating %s" % threadAlive, alive['aliveFlag'];

break

def subprocess(aliveFlag, threadNum, threadAlive):

t = Thread(target=control_listener, args=(aliveFlag, threadAlive))

count = 0

threadVal = threadNum

t.start()

run = alive['subAlive'];

while run == True:

print "Thread alive %s" % alive['aliveFlag'];

print "Thread %d Run number = %d" % (threadVal, count), alive['subAlive'];

count = count + 1

run = alive['subAlive'];

def testprocess(aliveFlag, threadNum, threadAlive):

t = Thread(target=control_listener, args=(aliveFlag, threadAlive))

count = 0

threadVal = threadNum

t.start()

run = alive['testAlive'];

while run == True:

print "This is a different thread %d Run = %d" % (threadVal, count)

count = count + 1

run = alive['testAlive'];

runNum = int(raw_input("Enter a number: "))

threadNum = int(raw_input("Enter number of threads: "))

print "Starting threads"

for i in range(threadNum):

p = Process(target=subprocess, args=('subKill', i, 'subAlive'))

p.start()

print "Subprocess started"

for i in range(threadNum):

p2 = Process(target=testprocess, args=('subKill', i, 'testAlive'))

p2.start()

print "Testproccess started"

print "Starting run"

time.sleep(runNum)

print "Terminating Subprocess run"

for i in range(threadNum):

alive['subKill'] = "kill";

print "Subkill = %s" % alive['subKill'];

print "Testprocess termination alive", alive['subAlive'];

print "Terminating Testprocess run"

for i in range(threadNum):

alive['subKill'] = "kill";

print "Testprocess termination alive", alive['subAlive'];

p.join()

p2.join()

相关阅读:
Top