Open In App

Non-Repeating Elements of a given array using Multithreaded program

Last Updated : 05 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report


Given an array arr[] of size N and an integer T representing the count of threads, the task is to find all non-repeating array elements using multithreading.

Examples:

Input: arr[] = { 1, 0, 5, 5, 2}, T = 3 
Output: 0 1 2 
Explanation: 
The frequency of 0 in the array arr[] is 1. 
The frequency of 1 in the array arr[] is 1. 
The frequency of 2 in the array arr[] is 1. 
Therefore, the required output is 0 1 2

Input: arr[] = { 1, 1, 5, 5, 2, 4 }, T = 3 
Output: 2 4 
Explanation: 
The frequency of 2 in the array arr[] is 1. 
The frequency of 4 in the array arr[] is 1. 
Therefore, the required output is 2 4

Approach: The idea is to use the pthread library available in C++ to create multiple threads for concurrent process flow and perform multiple operations( pthread create, pthread join , lock, etc) in multithreaded program. Follow the steps below to solve the problem:

  • Divide the array into T subarrays, such that each subarray of size N / T will be executed in a single thread.
  • Initialize a Map, say mp, to store the frequencies of each array element.
  • Create a pthread_mutex_lock, say lock1, to ensure that all threads do not trip over each other and corrupt the Map container.
  • Define a function func() for executing the body of a thread. This function is often called the kernel of the thread and is provided during thread creation.
    • Lock the current thread using pthread_mutex_lock() so that it does not overlap with other threads
    • Traverse through the given range as an argument to the function func() in the array arr[] and increment the frequency of the array element which is encountered.
    • Release the current thread using the function pthread_mutex_unlock().
  • Initialize an array, say thread[], of type pthread_t for storing the threads.
  • Iterate over the range [0, T] and create a thread by calling pthread_create() function and store it in the thread[i]
  • While each thread performs their individual tasks, the main() function will need to wait till each of the threads finish their work. 
    • Use pthread_join() function for waiting till each thread finishes executing function func()
    • Iterate over the range [0, T] and call pthread_create() function for each thread[i]
  • Finally, traverse the map mp and print the element occurring only once.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Time Complexity: O(N * log(N))
Auxiliary Space: O(N)

Note: It is recommended to execute the program in a Linux based system using the following command:

g++ -pthread program_name.cpp


Next Article

Similar Reads