为什么我的python线程不会对全局变量做出反应

时间:2013-07-24 16:55:36

标签: python variables global multiprocess

此代码用于启动和停止各种不同线程类型的多个副本。我将在前言中说我尝试使用管道来控制线程,但不断得到与管道有关的随​​机内存错误。这是一个工厂的原型,可以生成多个线程类型的多个副本,所以队列方法对我来说似乎并不实用,不过如果有什么我想念的话我都是耳朵。所以我最新的计划是使用一个全局字典,每个字符和线程终止条件具有不同的条目。即sub[Alive] subKill["kill"]

但由于某些原因,进程产生的control_listener线程不会触发kill条件,也不会读取全局变量。

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

0 个答案:

没有答案