sgn.subprocess
¶
Parallelize
¶
Bases: SignalEOS
flowchart TD
sgn.subprocess.Parallelize[Parallelize]
sgn.sources.SignalEOS[SignalEOS]
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
click sgn.subprocess.Parallelize href "" "sgn.subprocess.Parallelize"
click sgn.sources.SignalEOS href "" "sgn.sources.SignalEOS"
A context manager for running SGN pipelines with elements that implement separate processes or threads.
This class manages the lifecycle of workers (processes or threads) in an SGN pipeline, handling worker creation, execution, and cleanup. It also supports shared memory objects that will be automatically cleaned up on exit through the to_shm() method (only applicable for process mode).
Key features include: - Automatic management of worker lifecycle (creation, starting, joining, cleanup) - Shared memory management for efficient data sharing (process mode only) - Signal handling coordination between main process/thread and workers - Resilience against KeyboardInterrupt (Ctrl+C) - workers catch and ignore these signals, allowing the main process to coordinate a clean shutdown - Orderly shutdown to ensure all resources are properly released - Support for both multiprocessing and threading concurrency models - Automatic detection and invocation when pipeline.run() is called
IMPORTANT: When using process mode, code using Parallelize MUST be wrapped within an if name == "main": block. This is required because SGN uses Python's multiprocessing module with the 'spawn' start method, which requires that the main module be importable.
Supported usage — sequential pipelines only. The design supports a single
active Parallelize instance at a time, and multiple pipelines must be
run one after another (with p1: ... finishes before with p2: ...
begins). ParallelizeBase subclasses register themselves on a
class-level "pending" list at construction time; the next
Parallelize(...) instance claims that pending list and owns it for the
rest of its lifecycle. To keep each pipeline's elements isolated on its
own Parallelize, construct every element (and every to_shm()
segment) belonging to a pipeline before constructing its
Parallelize, and only then move on to constructing the next pipeline.
Unsupported usage:
- Concurrent multi-pipeline (two threads each driving a
Parallelize) is not supported. The class-level pending list is shared mutable state, so two threads constructing elements andParallelizeinstances interleaved will claim each other's elements. No locking is performed. - Nested context managers (
with p1: with p2: ...) is not supported. AlthoughParallelize's own per-instance state (the claimedinstance_listandshm_list) survives nesting cleanly,Parallelizeinherits from :class:~sgn.sources.SignalEOS, whose__enter__/__exit__use a single class-levelprevious_handlersdict rather than a stack. Nesting causes the inner__enter__to overwrite the outer's saved signal handlers, so the original handlers are leaked away on outer__exit__.rcvd_signalsis also wiped on each__exit__, so a signal received during the outer context can be dropped by the inner exit.
Shared memory cleanup: segments registered via to_shm() are normally
unlinked when Parallelize.__exit__ runs. As a safety net, an :mod:atexit
hook calls :meth:cleanup_all_shm on interpreter shutdown to release any
segments still tracked, and you can call :meth:cleanup_all_shm directly
from an error-handling path or interactively to recover from a leak.
Example with automatic parallelization (RECOMMENDED): def main(): pipeline = Pipeline() # Add ParallelizeTransformElement, ParallelizeSinkElement, etc. pipeline.run() # Automatically detects and enables parallelization
if __name__ == "__main__":
main()
Example with manual context manager (LEGACY): def main(): pipeline = Pipeline() with Parallelize(pipeline) as parallelize: parallelize.run()
if __name__ == "__main__":
main()
Source code in src/sgn/subprocess.py
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
__init__(pipeline=None, use_threading=None)
¶
Initialize the Parallelize context manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
Pipeline | None
|
The pipeline to run. |
None
|
use_threading
|
bool | None
|
Whether to use threading instead of multiprocessing. If not specified, uses the use_threading_default. |
None
|
Source code in src/sgn/subprocess.py
cleanup_all_shm()
classmethod
¶
Best-effort unlink of every shared memory segment tracked by Parallelize.
Walks two registries:
Parallelize.shm_list— pending segments registered byto_shmbut not yet claimed by aParallelizeinstance.Parallelize._live_instances— segments already claimed onto a liveParallelizeinstance whose__exit__has not run.
Every segment found is unlinked; FileNotFoundError (segment already
gone) is suppressed. The registries are cleared so a subsequent call
is a no-op.
Call this on an error path that bypasses the normal context-manager
cleanup, or interactively to recover from a leak. Also registered as
an :mod:atexit hook to catch the "user forgot with" case.
Source code in src/sgn/subprocess.py
needs_parallelization(pipeline)
staticmethod
¶
Check if a pipeline contains any elements that require parallelization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pipeline
|
Pipeline
|
The Pipeline instance to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the pipeline contains any Parallelize* elements. |
Source code in src/sgn/subprocess.py
run(threaded=None)
¶
Run the pipeline managed by this Parallelize instance.
This method executes the associated pipeline and ensures proper cleanup of worker resources, even in the case of exceptions. It signals all workers to stop when the pipeline execution completes or if an exception occurs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threaded
|
int | Executor | None
|
Forwarded to |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If an exception occurs during pipeline execution |
AssertionError
|
If no pipeline was provided to the Parallelize constructor. |
Source code in src/sgn/subprocess.py
to_shm(name, bytez, **kwargs)
staticmethod
¶
Create a shared memory object that can be accessed by subprocesses.
Note: This is only applicable in process mode. In thread mode, shared memory is not necessary since threads share the same address space.
This method creates a shared memory segment that will be automatically cleaned up when the Parallelize context manager exits. The shared memory can be used to efficiently share large data between processes without serialization overhead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Unique identifier for the shared memory block. |
required |
bytez
|
bytes | bytearray
|
Data to store in shared memory. |
required |
**kwargs
|
Any
|
Additional metadata to store with the shared memory reference. |
{}
|
Returns:
| Type | Description |
|---|---|
|
dict[str, Any]: A dictionary containing the shared memory object and metadata with keys: - "name": The name of the shared memory block - "shm": The SharedMemory object - Any additional key-value pairs from kwargs |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If shared memory with the given name already exists |
Example
shared_data = bytearray("Hello world", "utf-8") shm_ref = Parallelize.to_shm("example_data", shared_data)
Source code in src/sgn/subprocess.py
ParallelizeBase
dataclass
¶
Bases: Parallelize
flowchart TD
sgn.subprocess.ParallelizeBase[ParallelizeBase]
sgn.subprocess.Parallelize[Parallelize]
sgn.sources.SignalEOS[SignalEOS]
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeBase
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
click sgn.subprocess.ParallelizeBase href "" "sgn.subprocess.ParallelizeBase"
click sgn.subprocess.Parallelize href "" "sgn.subprocess.Parallelize"
click sgn.sources.SignalEOS href "" "sgn.sources.SignalEOS"
A mixin class for sharing code between ParallelizeTransformElement and ParallelizeSinkElement.
This class provides common functionality for both transform and sink elements that run in separate processes or threads. It handles the creation and management of communication queues, worker lifecycle events, and provides methods for worker synchronization and cleanup.
Key features: - Creates and manages worker communication channels (queues) - Handles graceful worker termination and resource cleanup - Provides resilience against KeyboardInterrupt - workers will catch and ignore KeyboardInterrupt signals, allowing the main process to handle them and coordinate a clean shutdown of all workers - Supports orderly shutdown to process remaining queue items before termination
This is an internal implementation class and should not be instantiated directly. Instead, use ParallelizeTransformElement or ParallelizeSinkElement.
Developer Usage
@dataclass class MyElement(ParallelizeTransformElement): multiplier: int = 2 threshold: float = 0.5
@staticmethod
def worker_process(
context: WorkerContext, multiplier: int, threshold: float
):
try:
frame = context.input_queue.get(timeout=1.0)
if frame and frame.data > threshold:
frame.data *= multiplier
context.output_queue.put(frame)
except queue.Empty:
pass
Note on reserved worker_process parameter names: framework attributes such as
in_queue, out_queue, worker, worker_stop, worker_shutdown,
terminated, at_eos, queue_maxsize, err_maxsize,
_use_threading_override, use_threading, pipeline, and
frame_factory MUST NOT be used as worker_process parameter names.
See _RESERVED_WORKER_PARAM_NAMES for the full list. The framework will
raise ValueError if a collision is detected.
Source code in src/sgn/subprocess.py
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 | |
check_worker_terminated()
¶
Check for premature worker termination.
This method verifies that the worker has not terminated before reaching End-Of-Stream (EOS). It is used internally to detect abnormal worker termination.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the worker has terminated but has not reached EOS, chained with the original worker exception if available |
Source code in src/sgn/subprocess.py
get_worker_exception()
¶
Get the worker exception if available, returning None if no exception.
Source code in src/sgn/subprocess.py
internal()
¶
Element hook invoked between sink and source pads.
Forwards to :meth:check_worker_terminated so that the pipeline raises
promptly if the worker died before EOS. The concrete element subclasses
below re-bind internal to this method because, due to MRO, they
would otherwise inherit Element.internal (a no-op) from
TransformElement/SinkElement/SourceElement before reaching
ParallelizeBase.
Source code in src/sgn/subprocess.py
sub_process_shutdown(timeout=0)
¶
Initiate an orderly shutdown of the worker.
This method signals the worker to complete processing of any pending data and then terminate. It waits for the worker to indicate completion, and collects any remaining data from the output queue before cleaning up resources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
int
|
Maximum time in seconds to wait for the worker to terminate. Defaults to 0 (wait indefinitely). |
0
|
Returns:
| Type | Description |
|---|---|
|
list[Any]: Any remaining items from the output queue. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the worker does not terminate within the specified timeout. |
Source code in src/sgn/subprocess.py
worker_process(context, *args, **kwargs)
¶
Override this method in subclasses to implement worker logic.
This method should be implemented as a static method or avoid accessing instance attributes directly to prevent pickling issues in multiprocessing mode. All necessary data should be passed through the method parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
WorkerContext
|
WorkerContext with clean access to queues and events |
required |
*args
|
Any
|
Automatically extracted instance attributes |
()
|
**kwargs
|
Any
|
Automatically extracted instance attributes with defaults |
{}
|
Source code in src/sgn/subprocess.py
ParallelizeSinkElement
dataclass
¶
Bases: SinkElement, ParallelizeBase, Parallelize
flowchart TD
sgn.subprocess.ParallelizeSinkElement[ParallelizeSinkElement]
sgn.base.SinkElement[SinkElement]
sgn.base.ElementLike[ElementLike]
sgn.base.UniqueID[UniqueID]
sgn.subprocess.ParallelizeBase[ParallelizeBase]
sgn.subprocess.Parallelize[Parallelize]
sgn.sources.SignalEOS[SignalEOS]
sgn.base.SinkElement --> sgn.subprocess.ParallelizeSinkElement
sgn.base.ElementLike --> sgn.base.SinkElement
sgn.base.UniqueID --> sgn.base.ElementLike
sgn.subprocess.ParallelizeBase --> sgn.subprocess.ParallelizeSinkElement
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeBase
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeSinkElement
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
click sgn.subprocess.ParallelizeSinkElement href "" "sgn.subprocess.ParallelizeSinkElement"
click sgn.base.SinkElement href "" "sgn.base.SinkElement"
click sgn.base.ElementLike href "" "sgn.base.ElementLike"
click sgn.base.UniqueID href "" "sgn.base.UniqueID"
click sgn.subprocess.ParallelizeBase href "" "sgn.subprocess.ParallelizeBase"
click sgn.subprocess.Parallelize href "" "sgn.subprocess.Parallelize"
click sgn.sources.SignalEOS href "" "sgn.sources.SignalEOS"
A Sink element that runs data consumption logic in a separate process or thread.
This class extends the standard SinkElement to execute its processing in a separate worker (process or thread). It communicates with the main process/thread through input and output queues, and manages the worker lifecycle. Subclasses must implement the worker_process method to define the consumption logic that runs in the worker.
The design intentionally avoids passing class or instance references to the worker to prevent pickling issues when using process mode. Instead, it passes all necessary data and resources via function arguments.
The implementation includes special handling for KeyboardInterrupt signals. When Ctrl+C is pressed in the terminal, workers will catch and ignore the KeyboardInterrupt, allowing them to continue processing while the main process coordinates a graceful shutdown. This prevents data loss and ensures all resources are properly cleaned up.
Attributes:
| Name | Type | Description |
|---|---|---|
queue_maxsize |
int
|
Maximum size of the communication queues |
err_maxsize |
int
|
Maximum size for error data |
_use_threading_override |
bool
|
Set to True to use threading or False to use multiprocessing. If not specified, uses the Parallelize.use_threading_default |
Example with default process mode
@dataclass class MyLoggingSinkElement(ParallelizeSinkElement): def pull(self, pad, frame): if frame.EOS: self.mark_eos(pad) # Send the frame to the worker self.in_queue.put((pad.name, frame))
def worker_process(self, context: WorkerContext):
try:
# Get data from the main process/thread
pad_name, frame = context.input_queue.get(timeout=0.1)
# Process or log the data
if not frame.EOS:
print(f"Sink received on {pad_name}: {frame.data}")
else:
print(f"Sink received EOS on {pad_name}")
except queue.Empty:
pass
Example with thread mode
@dataclass class MyThreadedSinkElement(ParallelizeSinkElement): _use_threading_override = True # Implementation same as above
Source code in src/sgn/subprocess.py
ParallelizeSourceElement
dataclass
¶
Bases: SourceElement, ParallelizeBase, Parallelize
flowchart TD
sgn.subprocess.ParallelizeSourceElement[ParallelizeSourceElement]
sgn.base.SourceElement[SourceElement]
sgn.base.ElementLike[ElementLike]
sgn.base.UniqueID[UniqueID]
sgn.subprocess.ParallelizeBase[ParallelizeBase]
sgn.subprocess.Parallelize[Parallelize]
sgn.sources.SignalEOS[SignalEOS]
sgn.base.SourceElement --> sgn.subprocess.ParallelizeSourceElement
sgn.base.ElementLike --> sgn.base.SourceElement
sgn.base.UniqueID --> sgn.base.ElementLike
sgn.subprocess.ParallelizeBase --> sgn.subprocess.ParallelizeSourceElement
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeBase
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeSourceElement
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
click sgn.subprocess.ParallelizeSourceElement href "" "sgn.subprocess.ParallelizeSourceElement"
click sgn.base.SourceElement href "" "sgn.base.SourceElement"
click sgn.base.ElementLike href "" "sgn.base.ElementLike"
click sgn.base.UniqueID href "" "sgn.base.UniqueID"
click sgn.subprocess.ParallelizeBase href "" "sgn.subprocess.ParallelizeBase"
click sgn.subprocess.Parallelize href "" "sgn.subprocess.Parallelize"
click sgn.sources.SignalEOS href "" "sgn.sources.SignalEOS"
A Source element that generates data in a separate process or thread.
This class extends the standard SourceElement to execute its data generation logic in a separate worker (process or thread). It communicates with the main process through output queues, and manages the worker lifecycle. Subclasses must implement the worker_process method to define the data generation logic that runs in the worker.
The design intentionally avoids passing class or instance references to the worker to prevent pickling issues when using process mode. Instead, it passes all necessary data and resources via function arguments.
The implementation includes special handling for KeyboardInterrupt signals. When Ctrl+C is pressed in the terminal, workers will catch and ignore the KeyboardInterrupt, allowing them to continue processing while the main process coordinates a graceful shutdown. This prevents data loss and ensures all resources are properly cleaned up.
Attributes:
| Name | Type | Description |
|---|---|---|
queue_maxsize |
int
|
Maximum size of the communication queues |
err_maxsize |
int
|
Maximum size for error data |
frame_factory |
Callable
|
Function to create Frame objects |
at_eos |
bool
|
Flag indicating if End-Of-Stream has been reached |
_use_threading_override |
bool
|
Set to True to use threading or False to use multiprocessing. If not specified, uses the Parallelize.use_threading_default |
Example with default process mode
@dataclass class MyDataSourceElement(ParallelizeSourceElement): def post_init(self): super().post_init() # Dictionary to track EOS status for each pad self.pad_eos = {pad.name: False for pad in self.source_pads}
def new(self, pad):
# Check if this pad has already reached EOS
if self.pad_eos[pad.name]:
return Frame(data=None, EOS=True)
try:
# Get data generated by the worker
# In a real implementation, you might use pad-specific queues
# or have the worker send pad-specific data
data = self.out_queue.get(timeout=1)
# Check for EOS signal (None typically indicates EOS)
if data is None:
self.pad_eos[pad.name] = True
# If all pads have reached EOS, set global EOS flag
if all(self.pad_eos.values()):
self.at_eos = True
return Frame(data=None, EOS=True)
# For data intended for other pads, you might implement
# custom routing logic here
return Frame(data=data)
except queue.Empty:
# Return an empty frame if no data is available
return Frame(data=None)
def worker_process(self, context: WorkerContext):
# Generate data and send it back to the main process/thread
for i in range(10):
if context.should_stop():
break
context.output_queue.put(f"Generated data {i}")
time.sleep(0.5)
# Signal end of stream with None
context.output_queue.put(None)
# Wait for worker_stop before terminating
# This prevents "worker stopped before EOS" errors
while not context.should_stop():
time.sleep(0.1)
Example with thread mode
@dataclass class MyThreadedSourceElement(ParallelizeSourceElement): _use_threading_override = True
def __post_init__(self):
super().__post_init__()
# Dictionary to track EOS status for each pad
self.pad_eos = {pad.name: False for pad in self.source_pads}
def new(self, pad):
# Similar implementation as in the process mode example,
# but might use threading-specific features if needed
if self.pad_eos[pad.name]:
return Frame(data=None, EOS=True)
# Rest of implementation same as the process mode example
Source code in src/sgn/subprocess.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 | |
ParallelizeTransformElement
dataclass
¶
Bases: TransformElement, ParallelizeBase, Parallelize
flowchart TD
sgn.subprocess.ParallelizeTransformElement[ParallelizeTransformElement]
sgn.base.TransformElement[TransformElement]
sgn.base.ElementLike[ElementLike]
sgn.base.UniqueID[UniqueID]
sgn.subprocess.ParallelizeBase[ParallelizeBase]
sgn.subprocess.Parallelize[Parallelize]
sgn.sources.SignalEOS[SignalEOS]
sgn.base.TransformElement --> sgn.subprocess.ParallelizeTransformElement
sgn.base.ElementLike --> sgn.base.TransformElement
sgn.base.UniqueID --> sgn.base.ElementLike
sgn.subprocess.ParallelizeBase --> sgn.subprocess.ParallelizeTransformElement
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeBase
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
sgn.subprocess.Parallelize --> sgn.subprocess.ParallelizeTransformElement
sgn.sources.SignalEOS --> sgn.subprocess.Parallelize
click sgn.subprocess.ParallelizeTransformElement href "" "sgn.subprocess.ParallelizeTransformElement"
click sgn.base.TransformElement href "" "sgn.base.TransformElement"
click sgn.base.ElementLike href "" "sgn.base.ElementLike"
click sgn.base.UniqueID href "" "sgn.base.UniqueID"
click sgn.subprocess.ParallelizeBase href "" "sgn.subprocess.ParallelizeBase"
click sgn.subprocess.Parallelize href "" "sgn.subprocess.Parallelize"
click sgn.sources.SignalEOS href "" "sgn.sources.SignalEOS"
A Transform element that runs processing logic in a separate process or thread.
This class extends the standard TransformElement to execute its processing in a separate worker (process or thread). It communicates with the main process/thread through input and output queues, and manages the worker lifecycle. Subclasses must implement the worker_process method to define the processing logic that runs in the worker.
The design intentionally avoids passing class or instance references to the worker to prevent pickling issues when using process mode. Instead, it passes all necessary data and resources via function arguments.
The implementation includes special handling for KeyboardInterrupt signals. When Ctrl+C is pressed in the terminal, workers will catch and ignore the KeyboardInterrupt, allowing them to continue processing while the main process coordinates a graceful shutdown. This prevents data loss and ensures all resources are properly cleaned up.
Attributes:
| Name | Type | Description |
|---|---|---|
queue_maxsize |
int
|
Maximum size of the communication queues |
err_maxsize |
int
|
Maximum size for error data |
at_eos |
bool
|
Flag indicating if End-Of-Stream has been reached |
_use_threading_override |
bool
|
Set to True to use threading or False to use multiprocessing. If not specified, uses the Parallelize.use_threading_default |
Example with default process mode
@dataclass class MyProcessingElement(ParallelizeTransformElement): multiplier: int = 2 # Instance attributes become worker parameters
def pull(self, pad, frame):
# Send the frame to the worker
self.in_queue.put(frame)
if frame.EOS:
self.at_eos = True
def worker_process(self, context: WorkerContext, multiplier: int):
# Process data in the worker using the clean context
try:
frame = context.input_queue.get(timeout=0.1)
if frame and not frame.EOS:
frame.data *= multiplier
context.output_queue.put(frame)
except queue.Empty:
pass
def new(self, pad):
# Get processed data from the worker
return self.out_queue.get()
Example with thread mode
@dataclass class MyThreadedElement(ParallelizeTransformElement): _use_threading_override = True # Implementation same as above
Example
@dataclass class MyProcessingElement(ParallelizeTransformElement): multiplier: int = 2 threshold: float = 0.5
def pull(self, pad, frame):
self.in_queue.put(frame)
if frame.EOS:
self.at_eos = True
def worker_process(
self, context: WorkerContext, multiplier: int, threshold: float
):
try:
frame = context.input_queue.get(timeout=0.1)
if frame and not frame.EOS and frame.data > threshold:
frame.data *= multiplier
context.output_queue.put(frame)
except queue.Empty:
pass
def new(self, pad):
return self.out_queue.get()
Source code in src/sgn/subprocess.py
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 | |
QueueProtocol
¶
Bases: Protocol
flowchart TD
sgn.subprocess.QueueProtocol[QueueProtocol]
click sgn.subprocess.QueueProtocol href "" "sgn.subprocess.QueueProtocol"
Protocol defining a common Queue interface.
Source code in src/sgn/subprocess.py
QueueWrapper
¶
A wrapper that provides a unified interface for both Queue implementations.
This abstraction handles the differences between multiprocessing.Queue and queue.Queue APIs, specifically providing no-op implementations for multiprocessing-specific methods when wrapping a queue.Queue.
Source code in src/sgn/subprocess.py
WorkerContext
¶
Context object passed to worker methods with clean access to resources.