python中通过线程修改和访问不同类的变量

2024-09-28 05:17:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生。所以我问的可能不对。我想做的是。从mainss创建一个线程并启动该线程。当线程启动时,我希望它访问mainss类中创建线程的变量,并修改变量值。我希望mainss的执行休眠,直到线程修改它的一个变量值。我怎样才能做到这一点?下面是我尝试的代码。mythread.py类代码中的注释是我需要修改mainss类count变量值的地方

主.py

#!/usr/bin/python
import time
from myThread import myThread

class mainss():

    def __init__(self):
        print "s"

    def callThread(self):
        global count
        count = 1
        # Create new threads
        thread1 = myThread(1, "Thread-1", 1, count)
        thread1.start()
        # time.sleep(10) until count value is changed by thread to 3
        print "Changed Count value%s " % count
        print "Exiting"

m = mainss()
m.callThread()

神话阅读.py

#!/usr/bin/python

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter, count):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.count = count
    def run(self):
        print_time(self.name, 1, 5, self.count)

def print_time(threadName, delay, counter, count):
    from main import mainss
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        count = count + 1
        print "count %s" % (count)

        # here i want to modify count of mainss class

        counter -= 1

提前谢谢


Tags: namepyimportselftimeinitdefcount
2条回答

使用多处理,管理器字典用于在进程之间或进程与进程之间进行通信https://pymotw.com/3/multiprocessing/communication.html#managing-shared-state请注意,可以在进程运行时更改管理器字典。多重处理还有一个等待特性https://pymotw.com/3/multiprocessing/communication.html#signaling-between-processes

我会使用^{}^{}

类似的东西,(请注意,我没有亲自测试,显然你必须做一些更改。)

main.py

import Queue
import threading

from myThread import myThread

class mainss:

     def __init__(self):
         self.queue = Queue.Queue()
         self.event = threading.Event()

     def callThread(self):
         self.queue.put(1) # Put a value in the queue

         t = myThread(self.queue, self.event)
         t.start()

         self.event.wait() # Wait for the value to update

         count = self.queue.get()

         print "Changed Count value %s" % count

if __name__ == '__main__':
    m = mainss()
    m.callThread()

myThread.py

import threading

class myThread(threading.Thread):

    def __init__(self, queue, event):
        super(myThread, self).__init__()
        self.queue = queue
        self.event = event

    def run(self):
        while True:
            count = self.queue.get() # Get the value (1)

            count += 1

            print "count %s" % (count)

            self.queue.put(count) # Put updated value

            self.event.set() # Notify main thread

            break

相关问题 更多 >

    热门问题