Maison  >  Article  >  développement back-end  >  Recherche linéaire utilisant le multithreading en C

Recherche linéaire utilisant le multithreading en C

WBOY
WBOYavant
2023-09-06 17:13:06825parcourir

Recherche linéaire utilisant le multithreading en C

Ici, nous verrons comment appliquer le concept multi-threading pour rechercher un élément dans un tableau. La méthode ici est très simple. Nous allons créer quelques threads, puis diviser le tableau en différentes parties. Différents sujets rechercheront dans différentes parties. Plus tard, lorsque l'élément est trouvé, activez les indicateurs pour identifier l'élément.

Exemple

#include <stdio.h>
#include <pthread.h>
#define MAX 16
#define THREAD_MAX 4
int array[MAX] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };
int key = 18;
int flag = 0; //flag to indicate that item is found in the array or not
int current_thread = 0;
void* ThreadSearch(void* args) { //This is linear search function. It will be running using all threads
   int num = current_thread++;
   for (int i = num * (MAX / 4); i < ((num + 1) * (MAX / 4)); i++){
      if (array[i] == key)
         flag = 1; //set flag if key is found
   }
}
int main() {
   pthread_t thread[THREAD_MAX];
   for (int i = 0; i < THREAD_MAX; i++) { //create multiple threads
      pthread_create(&thread[i], NULL, ThreadSearch, (void*)NULL);
   }
   for (int i = 0; i < THREAD_MAX; i++) {
      pthread_join(thread[i], NULL); //wait untill all of the threads are completed
   }
   if (flag == 1)
      printf("Key element is found</p><p>");
   else
      printf("Key element is not present</p><p>");
}

Sortie

$ gcc 1249.Thread_search.cpp -lpthread
$ ./a.out
Key element is found

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer