簡體   English   中英

Python將變量發送給線程

[英]Python send variables to thread

我正在嘗試在Python2.7中創建自己的線程類。 我希望它能夠使用我自己的類函數來停止該線程。 目前我有這樣的事情:

class loop(threading.Thread):
  def __init__(self, myvar):
    super(loop, self).__init__()
    self.terminate = False
    self.myvar = myvar

  def run(self):
    while not self.terminate:
      do.smthng.useful(self.myvar)

  def change(self, newvar):
    self.myvar = newvar #Doesnt work, in run() my old var is still being used

  def stoploop(self):
    self.terminate = True #Also not working

l = loop(1)
l.start()
time.sleep(1)
l.change(2) #thread still using "1"
time.sleep(1)
l.stoploop() #doesnt stop

我在這里讀過一些關於此的帖子,但它不是我需要的。 任何幫助,將不勝感激。 謝謝。

編輯:正如一些評論者已經說過的那樣,這部分代碼看起來真的很有用! 問題出在我項目的另一個地方。 我找到了它,但無法解決它。 也許有些人可以提供幫助。

所以,我的項目使用Apache Thrift庫,服務器使用python。 Server.py:

loo = loop(0)
handler = ServHandler(loo)
processor = serv.Processor(handler)
transport = TSocket.TServerSocket('0.0.0.0', port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
server = TProcessPoolServer.TProcessPoolServer(processor, transport, tfactory, pfactory)
print 'Starting the server...'
server.serve()

ServHandler.py:

class ServHandler:
  def __init__(self, loo):
    self.loo = loo

  def terminate(self):  #Function that can be called remotely
    self.loo.stoploop() #Doesn't work

在上面的情況下,線程沒有終止,我不知道為什么。 沒有錯誤,對象存在,但它在其他地方設置self.terminate值。 對象id似乎和內存地址一樣,但它只是看起來像對象是不同的雖然循環init函數只被調用一次...

下面是循環成功終止的示例。 ServHandler.py:

 class ServHandler:
  def __init__(self, loo):
    self.loo = None

  def terminate(self):  #Function that can be called remotely
    self.loo.stoploop() #Does work!!!!!!

  def create(self):
    self.loo = loop(0)  #Function that can be called remotely

當我遠程創建循環對象時,我可以遠程終止它。 但它不適合我。 應該在服務thrift服務器之前創建一個線程,並且多個用戶必須能夠更改該線程的vars / terminate / etc。 我怎樣才能做到這一點? 謝謝!

不是每個sae的答案,而是OP的有用調試代碼

from time import sleep
from threading import Thread

class loop(Thread):
    def __init__(self, myvar):
        Thread.__init__(self)
        self.terminate = False
        self.myvar = myvar

    def run(self):
        while self.terminate is False:
            print('Run says myvar is:',self.myvar)
            sleep(0.5)

    def change(self, newvar):
        self.myvar = newvar

    def stoploop(self):
        self.terminate = True

l = loop(1)
l.start()
sleep(1)
l.change(2)
sleep(1)
l.stoploop()
print('Final product:',l.myvar)
sleep(2)
print('Is the thread alive:',l.isAlive())

用一些調試打印試驗你的代碼,它是否有效?
以下代碼生成:

[torxed@archie ~]$ python test.py 
Run says myvar is: 1
Run says myvar is: 1
Run says myvar is: 2        <-- Proves that change() does change `myvar`
Run says myvar is: 2
Final product: 2            <-- Also the global scope knows about the change
Is the thread alive: False  <-- And the thread got terminated as intended

但是,由於多種原因(甚至我自己不時使用此方法),這些在獲取數據或處理線程返回時不是防彈的想法,您應該考慮使用thread.join ,它應該與l.toplooop()結合使用l.toplooop()如下:

l = loop(1)
l.start()
l.change(2)
l.stoploop()
ret = l.join()

此外,在更新數據時,您應該獲取鎖定數據,以便不發生沖突,查看信號量對象。

這是你需要的嗎?

import threading
import time

class Worker(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.state = threading.Condition()
        self.variable = 10
        self.paused = False

    def run(self):
        while True:
            with self.state:
                if self.paused:
                    self.state.wait()
            self.do_stuff()

    def do_stuff(self):
        time.sleep(.1)
        print self.variable

    def resume(self):
        with self.state:
            self.paused = False
            self.state.notify()

    def pause(self):
        with self.state:
            self.paused = True


loop = Worker()
loop.start()
time.sleep(1)

loop.pause()
loop.variable = 11
print 'CHANGED!'
loop.resume()
time.sleep(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM