The container is single-threaded, so invoking methods on it from another thread is not safe (it would be nice if close() were an exception here, but I guess it is not).

What you can do is inject an application defined event into the loop to do the shutdown. E.g. as in attached modification to your example.
#!/usr/bin/env python

from proton.reactor import ApplicationEvent, Container, EventInjector
from proton.handlers import MessagingHandler
from proton import Message, Connection

import threading
import sys

class AmqpReceiver(MessagingHandler):
    def __init__(self):
        super(AmqpReceiver, self).__init__(prefetch=50)
        #self.host = "localhost:9001"
        self.host = "localhost"

        self.container = Container(self)
        self.events = EventInjector()
        self.container.selectable(self.events)
        self.conn = None
        self.receiver = None
        self.thread = threading.Thread(target=self.run)
        self.thread.daemon = True
        self.thread.start()

    def on_message(self, event):
        print("got message: event: ", event.message)

    def on_start(self, event):
        print("on start")
        self.conn = self.container.connect(self.host, reconnect=False)
        self.receiver = self.container.create_receiver(self.conn,
"test.awe.queue")

    def run(self):
        print("run container")
        self.container.run()
        print("after container.run()")
        sys.stdout.flush()

    def _stop(self):
        print('call stop')
        self.events.trigger(ApplicationEvent('stop'))
        print('call join')
        self.thread.join()
        print('done stop')

    def on_stop(self, event):
        print("on_stop")
        self.container.stop()

    def on_connection_closed(self, event):
        print("on_connection_closed")

    def on_session_closed(self, event):
        print("on_session_closed")

    def on_link_closed(self, event):
        print("on_link_closed")

    def on_disconnected(self, event):
        print("on_disconnected")


try:
    handler = AmqpReceiver()
    value = input("press enter")
    handler._stop()
except Exception as ex:
    print("got EXCEPTION")
    print(ex)

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to