Open In App

Search an Array using Multithreading in C

Last Updated : 23 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Searching arrays with a large number of elements can be time-consuming as the program will check all the elements one by one, which may lead to delays and underutilization of the CPU, as only a single core will be used.

By using Multithreading, we can utilise multiple CPU cores, which can simultaneously search different chunks of the array, and greatly reduce the search time to provide faster results.

Approach

We can create a search function that will create multiple threads, and each thread will search a specific portion of the given array to find the target element. Once all of the threads finish their task, the search function will print the results.

In the main function the user will have to simply call the search function, and the multithreading feature will be implemented via that search function.

Implementation

Step 1: Defining the main search function

The main search function that will be responsible for creating threads, defining the arguments for each thread and printing the results once all the threads finish their task.

The main search function will take 3 parameters:

  • int *array: the array which is to be searched.
  • int n: integer n representing the size of the array
  • int k: the target element.

Note: We will be passing the structure containing arguments by its value so that we can modify and use that same structure to pass arguments to the next thread and we do not have to create new structures for each thread.

Step 2: Defining the thread callable

The thread callable which are function that define the task which is to be performed by that thread. For this program the thread callable will search a specific chunk of the array and will modify the global variable (found) if the element is found.

Structure is used to pass multiple variables of to the function

Execution

In this step we set up the main function where we will define the array, the target element and call the search function on that array.

For this problem we are initialising the array with random values.

C
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdbool.h>

// Defining limits
#define MAX_SIZE 10
#define MAX_THREADS 5

// To store the index of k element
_Atomic int res_index = -1;

// Signals other threads to stop early
_Atomic bool found = false;

// Structure to pass args to thread
typedef struct thread_param {
    int *array;
    int start;
    int end;
    int k;
} Thread_param;

// Search function for chunk of array
void* thread_search(void *ptr) {
    Thread_param *args = (Thread_param*)ptr;

    for (int i = args->start;
         i < args->end; i++) {
        if (found) {
            free(ptr);
            pthread_exit(NULL);
        }
        if (args->array[i] == args->k) {
            if (!found) {
                found = true;
                res_index = i;
            }
            free(ptr);
            pthread_exit(NULL);
        }
    }
    free(ptr);
    pthread_exit(NULL);
}

int search_array(int *array, int n,
        int k) {
    pthread_t threads[MAX_THREADS];
    int chunk_size = n / MAX_THREADS;

    for (int i = 0; i < MAX_THREADS; i++) {
        Thread_param *args =
            malloc(sizeof(Thread_param));
        args->array = array;
        args->k = k;
        args->start = i * chunk_size;
        args->end = (i == MAX_THREADS - 1) ?
            n : (i + 1) * chunk_size;

        pthread_create(&threads[i], NULL,
            thread_search, args);
    }

    for (int i = 0; i < MAX_THREADS; i++)
        pthread_join(threads[i], NULL);

    if (res_index == -1)
        printf("Element Not Found");
    else
        printf("Element found at index: %d",
               res_index);
    return res_index;
}

int main() {
    int arr[MAX_SIZE];
    int n = sizeof(arr) / sizeof(arr[0]);
    srand(time(0));
    for (int i = 0;i < n; i++)
        arr[i] = rand() % n;

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    int k;
    printf("\nEnter Number to Search: ");
    scanf("%d", &k);

    search_array(arr, n, k);
    return 0;
}

Output:

2 9 1 3 0 9 2 3 9 3 
Enter Number to Search: 9
Element found at index: 5

Similar Reads