Linear search using Multi-threading
Given a large file of integers, search for a particular element in it using multi-threading.
Examples:
Input : 1, 5, 7, 10, 12, 14, 15, 18, 20,
22, 25, 27, 30, 64, 110, 220
Output :if key = 20
Key element found
Input :1, 5, 7, 10, 12, 14, 15, 18, 20,
22, 25, 27, 30, 64, 110, 220
Output :if key = 202
Key not present
Prerequisite : Multi-threading
Approach :
First create n threads. Then, divide array in to four parts one section for each thread and apply linear search on individual section using multhreading and check whether the key element is present or not.
Command : g++ -pthread linear_thread.cpp
C++
// CPP code to search for element in a // very large file using Multithreading #include <iostream> #include <pthread.h> using namespace std; // Max size of array #define max 16 // Max number of threads to create #define thread_max 4 int a[max] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 }; int key = 202; // Flag to indicate if key is found in a[] // or not. int f = 0; int current_thread = 0; // Linear search function which will // run for all the threads void* ThreadSearch(void* args) { int num = current_thread++; for (int i = num * (max / 4); i < ((num + 1) * (max / 4)); i++) { if (a[i] == key) f = 1; } } // Driver Code int main() { pthread_t thread[thread_max]; for (int i = 0; i < thread_max; i++) { pthread_create(&thread[i], NULL, ThreadSearch, (void*)NULL); } for (int i = 0; i < thread_max; i++) { pthread_join(thread[i], NULL); } if (f == 1) cout << "Key element found" << endl; else cout << "Key not present" << endl; return 0; } |
Output:
Key not present
Exercise: The above code divides array into four subarrays. Extend this to take a parameter that decides number of divisions (or threads).
Recommended Posts:
- Linear Search vs Binary Search
- Linear Search
- C/C++ Program for Linear Search
- Java Program for Linear Search
- Multithreading in C++
- Multithreading in C
- Repeatedly search an element by doubling it after every successful search
- Why is Binary Search preferred over Ternary Search?
- Interpolation search vs Binary search
- Best First Search (Informed Search)
- Median of two sorted arrays of different sizes | Set 1 (Linear)
- Sublist Search (Search a linked list in another list)
- Meta Binary Search | One-Sided Binary Search
- K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
- K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



