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


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);


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;

if (!flag)

return NULL;

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


One thought on “Application Of Threads For Solving Problems

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s