Skip to content

Instantly share code, notes, and snippets.

@morsik
Created October 4, 2011 18:34
Show Gist options
  • Save morsik/1262418 to your computer and use it in GitHub Desktop.
Save morsik/1262418 to your computer and use it in GitHub Desktop.
gcc primenumbers.c -o primenumbers -lpthread
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define THREADS_NUM 8
long long int count_to = 100;
void *thread_isPrimeNumber(void *arg)
{
long long int num = (long long int)arg;
long long int i;
char is_prime = 1;
while (num++)
{
if (num > count_to && count_to != 0)
break;
if (num % THREADS_NUM == (long long int)arg && (num % 2 != 0 || num % 3 != 0 || num % 5 != 0 || num % 7 != 0 || num % 9 != 0))
{
is_prime = 1;
for (i = 3; i < num; i=i+2)
{
if (num % i == 0)
{
is_prime = 0;
break;
}
}
if (is_prime)
printf("%i\n", num);
fflush(0);
}
}
return 0;
}
int main(int argc, char* argv[])
{
if (argc > 1)
count_to = atoi(argv[1]);
else
count_to = 100;
pthread_t pth[THREADS_NUM];
long long int i;
for (i = 0; i < THREADS_NUM; i++)
pthread_create(&pth[i], NULL, thread_isPrimeNumber, i);
for (i = 0; i < THREADS_NUM; i++)
pthread_join(pth[i], NULL);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment