简体   繁体   English

Python Thread类变量为空

[英]Python Thread class variable is blank

I've been trying to fix this issue for the past few hours, and i just can't figure out what i'm doing wrong! 在过去的几个小时中,我一直在尝试解决此问题,但我无法弄清自己在做什么错!

I have a single python file: 我有一个python文件:

REFRESH_RATE=10.0
MAX_SECONDS=30

class user_manager:
  users={}
  def __init__(self,queue,sign_properties):

    self.properties=sign_properties
    self.queue=queue
    self.lock=threading.Lock()
    t=threading.Thread(target=user_timer,args=(self.lock,))
    t.daemon=True
    t.start()

  def add_user(self,macaddr,user_properties):
    self.lock.acquire()
    user_manager.users[macaddr]=user(user_properties)
    self.lock.release()

  def user_exists(self, macaddr):
    if macaddr in user_manager.users:
      return True
    return False

  def update_rssi_for_user(self, macaddr,rssi):
    self.lock.acquire()
    user_manager.users[macaddr].update_rssi(rssi)
    self.lock.release()

  def get_users(self):
    return user_manager.users



def user_timer(lock):
  while True:
    print 'Test'
    lock.acquire()
    print user_manager.users
    lock.release()
    format = '%H:%M:%S'
    for user in user_manager.users:
      first_seen=user_manager.users[user].get_first_seen()
      current_time=str(datetime.datetime.now().time())
      difference=datetime.strptime(current_time, format) - datetime.strptime(first_seen[1], format)
      print 'difference'+str(difference.seconds)
      if difference.seconds >30:
        user.expire()
        del user_manager.users[user]
    time.sleep(REFRESH_RATE)

The idea is that the user_manager class has a class variable called users, that is populated during runtime - this works perfectly. 这个想法是,user_manager类具有一个名为users的类变量,该类变量在运行时填充-效果很好。

Then I have a threaded function called user_timer that is started from the user_manager, which manages these users and expires them after X amount of time. 然后,我有一个名为user_timer的线程函数,该函数从user_manager启动,该函数管理这些用户,并在X时间后使它们过期。 This is removed from the context of this post as it's not relevant. 由于该帖子不相关,因此已从本文的上下文中删除。

Currently, every time user_timer is called the result of user_manager.users is an empty dictionary {} but from outside of this file other modules can see the class variable as being populated. 当前,每次调用user_timer的结果都是user_manager.users是一个空字典{}但是从该文件之外,其他模块可以看到正在填充类变量。

What exactly am i doing wrong, and why does it work in this fashion? 我到底在做什么错,为什么它会以这种方式起作用?

James. 詹姆士。

EDIT: 编辑:

Calling class' constructor: 调用类的构造函数:

    class api_wrapper(object):
  def __init__(self,queue,display_queue,macaddr):
    self.properties={}
    self.queue=queue
    self.register_sign(macaddr)
    self.user_manager=user_manager(self.queue,self.properties)
    self.nearby_devices={}
    self.display_queue=display_queue

Calling function from the above class: 从上面的类中调用函数:

def handle_address(self,address,postcode):
if self.user_manager is None:
  return
if self.user_manager.user_exists(address):
  #print user_manager.users
  self.user_manager.update_address_for_user(address,postcode)
  #self.display_queue.put(self.user_manager.get_users())
elif macaddr not in self.nearby_devices:
  if self.check_address(address) is False:
    self.nearby_devices[address]=postcode

When I add enough around your code to get it to run, it works for me at least as far as getting an AttributeError: 'module' object has no attribute 'strptime' where you have mixed the datetime module with the datetime class within that module. 当我在代码中添加足够的代码以使其运行时,它至少对AttributeError: 'module' object has no attribute 'strptime' ,在该AttributeError: 'module' object has no attribute 'strptime'中您将datetime模块与该模块中的datetime类混合在一起。

Not a lot of help I know, but I suspect the problem must lie outside the code you posted. 我所知道的帮助不多,但是我怀疑问题可能出在您发布的代码之外。 user_timer sees the update to user_manager.users just fine: user_timer看到对user_manager.users的更新就好了:

import threading
import datetime

REFRESH_RATE=10.0
MAX_SECONDS=30

class user:
    def __init__(self, properties):
        self.properties = properties

    def get_first_seen(self):
        return 42

class user_manager:
  users={}
  def __init__(self,queue,sign_properties):

    self.properties=sign_properties
    self.queue=queue
    self.lock=threading.Lock()
    t=threading.Thread(target=user_timer,args=(self.lock,))
    t.daemon=True
    t.start()

  def add_user(self,macaddr,user_properties):
    self.lock.acquire()
    user_manager.users[macaddr]=user(user_properties)
    self.lock.release()

  def user_exists(self, macaddr):
    if macaddr in user_manager.users:
      return True
    return False

  def update_rssi_for_user(self, macaddr,rssi):
    self.lock.acquire()
    user_manager.users[macaddr].update_rssi(rssi)
    self.lock.release()

  def get_users(self):
    return user_manager.users



def user_timer(lock):
  while True:
    print 'Test'
    lock.acquire()
    print user_manager.users
    lock.release()
    format = '%H:%M:%S'
    for user in user_manager.users:
      first_seen=user_manager.users[user].get_first_seen()
      current_time=str(datetime.datetime.now().time())
      difference=datetime.strptime(current_time, format) - datetime.strptime(first_seen[1], format)
      print 'difference'+str(difference.seconds)
      if difference.seconds >30:
        user.expire()
        del user_manager.users[user]
    time.sleep(REFRESH_RATE)


u = user_manager(None, None)
u.add_user("1234", "Properties")
raw_input()

Give me this output: 给我这个输出:

C:\temp>c:\python27\python t.py
Test
{'1234': <__main__.user instance at 0x02583A80>}
Exception in thread Thread-1:
Traceback (most recent call last):
  File "c:\python27\lib\threading.py", line 810, in __bootstrap_inner
    self.run()
  File "c:\python27\lib\threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "t.py", line 55, in user_timer
    difference=datetime.strptime(current_time, format) - datetime.strptime(first_seen[1], format)
AttributeError: 'module' object has no attribute 'strptime'

Traceback (most recent call last):
  File "t.py", line 65, in <module>
    raw_input()
KeyboardInterrupt

I resolved this by spawning it as a Process instead and using the shared state variable of manager.Dict()! 我通过将其生成为Process并使用manager.Dict()的共享状态变量来解决此问题!

The thread i believe was copy the variables at the time of spawn, and because it was running in an almost 'separate' environment, the class variables weren't changing! 我相信线程是在生成时复制变量的,并且由于它是在几乎“单独”的环境中运行,因此类变量没有改变!

Thanks all. 谢谢大家

James. 詹姆士。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM