0

此代码用于启动和停止各种不同线程类型的多个副本。我会先说我尝试使用管道来控制线程,但不断收到与管道有关的随​​机内存错误。这是一个工厂的原型,用于生产多个线程类型的多个副本,因此队列方法对我来说似乎也不实用,尽管如果我缺少某些东西,我会全神贯注。所以我的最新计划是为每个线程和线程终止条件使用具有不同条目的全局字典。IEsub[Alive] subKill["kill"]

然而由于某种原因,control_listener进程产生的线程不会触发终止条件并且不会读取全局变量。

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()
4

0 回答 0