Fork join
Fork Join A fork join is a synchronization mechanism used in operating systems to synchronize multiple processes accessing shared resources. It involves two...
Fork Join A fork join is a synchronization mechanism used in operating systems to synchronize multiple processes accessing shared resources. It involves two...
Fork Join
A fork join is a synchronization mechanism used in operating systems to synchronize multiple processes accessing shared resources. It involves two or more processes executing a section of code independently, and only allowing them to proceed if they have completed their task and reached a designated synchronization point.
Steps of a Fork Join:
Forking: Each process creates a child process and copies its address space and the current process's resources into the child.
Synchronization: The parent process creates a synchronization object, such as a mutex or semaphore, and waits for all child processes to finish their tasks.
Waiting: The parent process waits for the child processes to complete their tasks and reach the synchronization object.
Joining: After all child processes have finished, the parent process joins the child process and waits for it to finish before continuing execution.
Example:
// Parent process
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
int main() {
// Create a semaphore with 2 threads
semaphore_t lock;
sem_init(&lock, 0, 2);
// Fork two child processes
pid_t child_pid1 = fork();
pid_t child_pid2 = fork();
// Wait for child processes to finish
if (child_pid1 == 0) {
// Child 1 code
printf("Child 1 done\n");
} else if (child_pid2 == 0) {
// Child 2 code
printf("Child 2 done\n");
}
// Join child process 1
sem_wait(&lock, 0);
// Join child process 2
sem_wait(&lock, 0);
return 0;
}
Benefits of Fork Join:
Ensures that only one process accesses a shared resource at a time, preventing inconsistencies.
Allows multiple processes to execute independently while avoiding deadlocks.
Simplifies synchronization and reduces complexity in multi-threaded applications.
Note:
A synchronization object is used to control access to shared resources.
The number of processes participating in the fork join should match the number of synchronization objects created.
The parent process waits for all child processes to reach the synchronization object before continuing execution