Python Forum
how to use thread without locking up terminal
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to use thread without locking up terminal
#8
actually everything looks fine. One important thing is that you declare a and mark it as global while using it in functions/methods. Here is you code but only with one observer and listener for now:
from asyncio.tasks import wait
import _thread

class Publisher(object):
 
	def __init__(self):
		self.subscribers = dict()
     
	def register(self, who, callback=None):
		if callback == None:
			callback = getattr(who, 'update')
		self.subscribers[who] = callback
     
	def unregister(self, who):
		del self.subscribers[who]
     
	def dispatch(self, message):
		for subscriber, callback in self.subscribers.items():
			callback(message)
     
### Script that listens to hid divice ###    
class HIDListen:
	def __init__(self, name):
		self.name = name
	def update(self, message):
		#print('{} got message "{}"'.format(self.name, message))
		global a
		a= message 
 
### User Script (Supposed to be simple for end-user)        
class HIDCtrl:
	def __init__(self, name):
		self.name = name
	def update(self, message):
	    #print('{} got message "{}"'.format(self.name, message))
		global a
		a= message 

# fake hid
def hid_run(hid):
	pub = Publisher()
	#HID = HIDListen('speaker')
	pub.register(hid, hid.update)
	b = 0
	while 1:
		pub.dispatch(b)
		b += 1
		wait(1)
	

# User friendly interface
a = -1
#pub = Publisher()
HID = HIDCtrl('listener')
_thread.start_new_thread ( hid_run, (HID, ))
#pub.register(HID, HID.update)
while 1:
	print(a)
Reply


Messages In This Thread
RE: how to use thread without locking up terminal - by ThiefOfTime - May-03-2018, 07:38 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020