Multiple Process Creation and Scheduling in OS: Practical Example with Code

Multiple Process Creation and Scheduling in OS: Practical Example with Code

Here's an example of how to create multiple processes, schedule them using priority scheduling, and execute a task in Python:

import multiprocessing
import heapq

def worker_task(task):
    print("Executing task:", task)

if __name__ == '__main__':
    # create a list of tasks with priorities
    tasks = [(1, "task 1"), (2, "task 2"), (3, "task 3"), (1, "task 4")]

    # create a process for each task
    processes = [multiprocessing.Process(target=worker_task, args=(task[1],)) for task in tasks]

    # define priority scheduling
    def priority_schedule(processes):
        heap = [(0, process) for process in processes]
        heapq.heapify(heap)
        while heap:
            priority, process = heapq.heappop(heap)
            yield process

    # create a priority scheduler
    scheduler = priority_schedule(processes)

    # execute each task using priority scheduling
    for i in range(len(tasks)):
        process = next(scheduler)
        process.start()
        process.join()

    print("All processes completed")

In this example, we create a list of tasks to be executed by each process, where each task is a tuple with a priority value and a string describing the task. We then create a separate process for each task using a list comprehension, similar to the previous examples.

We define a generator function priority_schedule() that takes a list of processes as input and yields each process in priority order. The priority of each process is determined by the priority value associated with its corresponding task.

We then create a priority scheduler using priority_schedule() and pass it the list of processes we created earlier.

We execute each task using priority scheduling by iterating through the list of tasks and starting each process returned by the scheduler using the start() method. We then wait for each process to complete using the join() method.

Note that in this example, we use a priority scheduler to execute the tasks, which means that processes with higher priority values are executed before processes with lower priority values. This can be useful for tasks that have different levels of importance or urgency.

Did you find this article valuable?

Support Bit Fetch by becoming a sponsor. Any amount is appreciated!