tcalmant / ipopo

iPOPO: a Service-Oriented Component Model for Python
https://ipopo.readthedocs.io/
Apache License 2.0
69 stars 28 forks source link

Pelix/iPOPO and multi-threading #82

Closed enferre closed 6 years ago

enferre commented 7 years ago

Dear Thomas, sometime requirements would need to implement two data-processing bundles running concurrently. Is the Python's Global Interpreter Lock (GIL) a limitation for Pelix/iPOPO to execute multi-threading applications?

Thanks again for your time. BR, Enrico

tcalmant commented 7 years ago

Hi Enrico,

Pelix/iPOPO will lock during bundle installation, start and stop operations, as well as service un/registration and component validation. This has been designed to avoid unwanted behaviors in most cases, most importantly to avoid having a service being unregistered while a component depending on it is validating.

Once the callback method of the bundle (start/stop) or component (validate, invalidate, ...) has returned, the lock is released. So the best practice is to return as fast as possible from those methods. The idea is to start a thread running heavy tasks when those methods are called.

As an example:

from pelix.constants import BundleActivator
import threading

@BundleActivator
class Activator:
    def __init__(self):
        self.event = threading.Event()
        self.thread = None

    def long_task(self):
        while not self.event.wait(1):
            print("Long task...")

    def start(self, context):
        self.event.clear()
        self.thread = threading.Thread(target=self.long_task)
        self.thread.start()

    def stop(self, context):
        self.event.set()
        self.thread.join()

Cheers, Thomas