首頁 > 後端開發 > C++ > 主體

使用C語言編寫的二分查找程序,使用pthread進行多執行緒處理

WBOY
發布: 2023-08-26 12:45:12
轉載
1203 人瀏覽過

使用C語言編寫的二分查找程序,使用pthread進行多執行緒處理

我們知道二分查找方法是一種最適合和有效的排序演算法。這個演算法適用於已排序的序列。演算法很簡單,它只是從中間找到元素,然後將列表分成兩部分,並向左子列表或右子列表移動。

我們知道它的演算法。現在我們將看到如何在多執行緒環境中使用二分查找技術。線程的數量取決於系統中存在的核心數。讓我們看一下程式碼以了解思路。

範例

#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
登入後複製

以上是使用C語言編寫的二分查找程序,使用pthread進行多執行緒處理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!