Home > Backend Development > C++ > Linear search using multithreading in C

Linear search using multithreading in C

WBOY
Release: 2023-09-06 17:13:06
forward
886 people have browsed it

Linear search using multithreading in C

Here we will see how to apply multi-threading concept to search for an element in an array. The method here is very simple. We will create some threads and then split the array into different parts. Different threads will search in different parts. Later, when the element is found, enable flags to identify the element.

Example

#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>");
}
Copy after login

Output

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

The above is the detailed content of Linear search using multithreading in C. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template