আমরা জানি যে বাইনারি অনুসন্ধান পদ্ধতি হল সবচেয়ে উপযুক্ত এবং কার্যকর সাজানোর অ্যালগরিদমগুলির মধ্যে একটি৷ এটি সাজানো ক্রম উপর কাজ করে. অ্যালগরিদমটি সহজ, এটি কেবল মাঝখান থেকে উপাদানটি খুঁজে পায়, তারপর তালিকাটিকে দুটি অংশে ভাগ করে এবং হয় বাম সাবলিস্ট বা ডান সাবলিস্টের দিকে চলে যায়৷
আমরা এর অ্যালগরিদম জানি। এখন আমরা দেখব কিভাবে মাল্টিথ্রেডিং পরিবেশে বাইনারি সার্চ টেকনিক ব্যবহার করা যায়। থ্রেডের সংখ্যা সিস্টেমে উপস্থিত কোরের সংখ্যার উপর নির্ভর করে। আসুন ধারণা পেতে কোডটি দেখি।
উদাহরণ
#include <iostream>
#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 < high
// or key is found in any portion of array
while (start < end && !found) { //if some other thread has got the element, it will stop
mid = (end - start) / 2 + start;
if (arr[mid] == key) {
found = true;
break;
}
else if (arr[mid] > key)
end = mid - 1;
else
start = mid + 1;
}
}
main() {
pthread_t threads[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; i++)
pthread_create(&threads[i], NULL, binary_search, (void*)NULL);
for (int i = 0; i < MAX_THREAD; i++)
pthread_join(threads[i], NULL); //wait, to join with the main thread
if (found)
cout << key << " found in array" << endl;
else
cout << key << " not found in array" << endl;
} আউটপুট
31 found in array