Skip to content

Instantly share code, notes, and snippets.

@atomictom
Created January 27, 2014 04:32
Show Gist options
  • Save atomictom/8643323 to your computer and use it in GitHub Desktop.
Save atomictom/8643323 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#define NUM_THREADS 2
#define PRIME_LIMIT ((int)1e9)
unsigned char sieve[PRIME_LIMIT];
void * print_hello(void * arg){
int thread_id = *(int *)arg;
printf("%d says \"Hi!\"\n", thread_id);
return NULL;
}
void * compute_primes(void * arg){
int thread_id = *(int *)arg;
int multiple = thread_id * 2 + 3;
int i;
while(multiple <= PRIME_LIMIT){
for(i = 0; i * multiple <= PRIME_LIMIT; i++){
if(sieve[i * multiple] < 100)
sieve[i * multiple] += 1;
/* if(sieve[i * multiple] >= 2){ */
/* break; */
/* } */
}
multiple += NUM_THREADS * 2;
}
return NULL;
}
int main(void){
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
int i, ret;
for(i = 0; i < NUM_THREADS; i++){
thread_ids[i] = i;
ret = pthread_create(&threads[i], NULL, &compute_primes, &thread_ids[i]);
if(ret){
printf("Thread creation failed with error: %d\n", ret);
}
}
for(i = 0; i < NUM_THREADS; i++){
pthread_join(threads[i], NULL);
}
long long int sum = 2;
int count = 1;
for(i = 3; i <= PRIME_LIMIT; i+=2){
if(sieve[i] == 1){
sum += i;
count++;
}
}
printf("Sum: %lld\n", sum);
printf("Count: %d\n", count);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment