在python中创建守护程序线程后无法访问变量

时间:2014-12-02 07:23:08

标签: python multithreading

这是我的第一个线程程序,我对操作系统概念完全陌生。我只是想了解如何使用python异步处理东西。我正在尝试建立一个会话并在守护程序线程上发送Keepalive并使用主线程发送协议消息。但是我注意到,一旦我创建了线程,我就无法访问在创建线程之前我能够访问的变量。在创建这个新线程之前,我没有看到过去常见的全局变量。

有人可以帮助我理解线程在这里是如何工作的。我想了解:

  • 如何正确打印以便日志记录有用。
  • 如何杀死我们创建的主题?
  • 如何从一个线程访问变量

    def pcep_init(ip):
        global pcc_client,keeppkt,pkt,thread1
        accept_connection(ip)
        send_pcep_open()
    
        # Create new Daemon thread to send KA
        thread1 = myThread(1, "Keepalive-Thread\r")
        thread1.setDaemon(True)
    
        # Start new Threads
        print "This is thread1 before start %r" % thread1
        thread1.start()
        print "This is thread1 after start %r" % thread1
        print "Coming out of pcep_init"
        return 1
    

然而,当我执行API时,我发现由于异步

,打印件没有错位
>>> ret_val=pcep_init("192.168.25.2"). 
starting pce server on 192.168.25.2 port 4189
connection from ('192.168.25.1', 42352)
, initial daemon)>fore start <myThread(Keepalive-Thread
, started daemon 140302767515408)>ead(Keepalive-Thread
Coming out of pcep_init
>>> Starting Keepalive-Thread <------ I am supposed to hit the enter button to get the python prompt not sure why thats needed.

>>> thread1
Traceback (most recent call last):
  File "<console>", line 1, in <module>
NameError: name 'thread1' is not defined

>>> threading.currentThread()
<_MainThread(MainThread, started)>
>>> threading.activeCount()
2
>>> threading.enumerate() <-------------- Not sure why this is not showing the Main Thread
, started daemon 140302767515408)>], <myThread(Keepalive-Thread
>>>                                                                                                 

0 个答案:

没有答案