Application Of Threads For Solving Problems

I am having operating system as one of the subject this semester. Recently I studied about forking a process and about threads, it’ s really an interesting topic indeed 🙂

I have written code for finding prime numbers between 1 and 100000000 using concept of threading. In this program two threads are getting created which runs independently and simultaneously thus calling  prime_number  function to calculate prime numbers between 1 to 50000 by thread1 and 50001 to 100000000 by thread2 respectively.This really speed up the calculation time as compared to a single program calculating prime numbers between 1 to 100000000.

/*
Objective : Finding all the prime numbers between 1 and 100000000 using threading
File Name : threadprime.c
Date : 8/09/2012
Author : Abhishek Kumar Singh
*/

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
#include<math.h>

void * prime_number(void * ptr);

int main()
{
const size_t limits[2] = {1, 100000000};
const size_t limits_thread1[2] = {2, (limits[1]/2)};
const size_t limits_thread2[2] = {(limits[1]/2 + 1), 10};
int iret1, iret2;

pthread_t thread1, thread2;

/* Create independent threads each of which will execute the prime_number function */
iret1 = pthread_create(&thread1, NULL, prime_number, (void*)limits_thread1);
iret2 = pthread_create(&thread2, NULL, prime_number, (void*)limits_thread2);

/* Wait till the threads are complete */
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

return EXIT_SUCCESS;
}

void *prime_number(void * ptr)
{
size_t temp;
size_t number;
size_t *limits = (size_t *)ptr;
size_t lower = *limits;
size_t upper = *(limits + 1);

for (number = lower; number <= upper; number++)
{
int flag = 0;
int temp1 = sqrt(number);

for (temp = 2; temp <= temp1; temp++)
{
if (number % temp == 0)
{
flag = 1;
break;
}
}

if (!flag)
printf("%d\n",number);
}

return NULL;
}

Note: compile this program as gcc -pthread threadprime.c -lm

Advertisements