import multiprocessing as mp
from queue import Queue

{% for stage_num in range(1, stage_count+1) %}
def stage{{stage_num}}_function(in_q, out_q):
    """Stage {{stage_num}} of the pipeline."""
    while True:
        item = in_q.get()
        if item is None:
            out_q.put(None)
            break

        # process item
{% for line in stage_bodies[stage_num-1] %}
        {{ line }}
{% endfor %}
        out_q.put(item)
{% endfor %}

def run_pipeline(input_data):
    """Run the pipeline on input_data."""
    # Create queues: one per stage plus one for final output
    queues = [mp.Queue() for _ in range({{stage_count}} + 1)]
    procs = []

    # Launch each stage as a separate process
    {% for stage_num in range(1, stage_count+1) %}
    p = mp.Process(
        target=stage{{stage_num}}_function,
        args=(queues[{{stage_num-1}}], queues[{{stage_num}}])
    )
    p.start()
    procs.append(p)
    {% endfor %}

    # Feed input data into the first stage
    for item in input_data:
        queues[0].put(item)
    queues[0].put(None)

    # Collect results from the last stage
    results = []
    while True:
        out = queues[-1].get()
        if out is None:
            break
        results.append(out)

    # Wait for all stages to finish
    for p in procs:
        p.join()

    return results

if __name__ == '__main__':
    data = {{input_data}}
    print(run_pipeline(data))
