Created
October 27, 2021 08:06
-
-
Save alirezaahani/8e4a5283f1ac59f2a47b2529aac7100c to your computer and use it in GitHub Desktop.
Multithreaded prime check in C ( using pthread )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <pthread.h> | |
#include <stdbool.h> | |
#include <pthread.h> | |
#define MAX_THREADS 64 | |
#define MAX_PRIMES 1000 | |
struct thread_info | |
{ | |
int low; | |
int high; | |
int number; | |
}; | |
volatile int running_threads = 0; | |
pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER; | |
void *prime_checker_thread(void *params) | |
{ | |
struct thread_info *data = (struct thread_info *) params; | |
for(int i = data->low; i < data->high; i++) | |
{ | |
int j = 2; | |
bool prime = true; | |
while(j * j < i) | |
{ | |
if(i % j == 0) | |
{ | |
prime = false; | |
} | |
j++; | |
} | |
if(prime) | |
{ | |
printf("TH: %d\tPRIME: %d\n", data->number, i); | |
} | |
} | |
pthread_mutex_lock(&running_mutex); | |
running_threads--; | |
pthread_mutex_unlock(&running_mutex); | |
return 0; | |
} | |
int main() | |
{ | |
int numbers = MAX_PRIMES; | |
int each_thread = numbers / MAX_THREADS; | |
struct thread_info thread_info_arr[MAX_THREADS]; | |
pthread_t threads[MAX_THREADS]; | |
for(int i = 0, j = 0; i < numbers - each_thread; i += each_thread, j++) | |
{ | |
thread_info_arr[j].low = i; | |
thread_info_arr[j].high = i + each_thread; | |
thread_info_arr[j].number = j; | |
pthread_mutex_lock(&running_mutex); | |
running_threads++; | |
pthread_mutex_unlock(&running_mutex); | |
pthread_create(&threads[j], NULL, prime_checker_thread, &thread_info_arr[j]); | |
} | |
while (running_threads > 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment