Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Binary Search using pthread in C Program?
We know that the binary search approach is one of the most suitable and effective sorting algorithm. This works on sorted sequence. The algorithm is simple, it simply finds the element from middle, then divide the list by two parts, and moves either towards the left sublist, or right sublist.
We know the algorithm of it. Now we will see how to use binary search technique in multithreading environment. The number of threads depends on number of cores are present in the system. Let us see the code to get the idea.
Example
#include#define MAX 16 #define MAX_THREAD 4 using namespace std; //place arr, key and other variables as global to access from different thread int arr[] = { 1, 6, 8, 11, 13, 14, 15, 19, 21, 23, 26, 28, 31, 65, 108, 220 }; int key = 31; bool found = false; int part = 0; void* binary_search(void* arg) { // There are four threads, each will take 1/4th part of the list int thread_part = part++; int mid; int start = thread_part * (MAX / 4); //set start and end using the thread part int end = (thread_part + 1) * (MAX / 4); // search for the key until low key) end = mid - 1; else start = mid + 1; } } main() { pthread_t threads[MAX_THREAD]; for (int i = 0; i Output
31 found in array
Advertisements
