📜  使用多线程进行线性搜索

📅  最后修改于: 2021-05-25 22:29:38             🧑  作者: Mango

给定一个很大的整数文件,请使用多线程在其中搜索特定元素。

例子:

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

先决条件:多线程

方法 :
首先创建n个线程。然后,将数组分为四个部分,每个线程一个部分,并使用多线程对单个部分进行线性搜索,并检查键元素是否存在。

Command : g++ -pthread linear_thread.cpp
C++
// CPP code to search for element in a
// very large file using Multithreading
#include 
#include 
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;
}


输出:

Key not present

练习:上面的代码将数组分为四个子数组。扩展它以获取一个决定分区(或线程)数量的参数。

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。