Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //--------------------------------------------
- // NAME: Antonio Milev
- // CLASS: XIb
- // NUMBER: 02
- // PROBLEM: #1
- // FILE NAME: primes.cc
- // FILE PURPOSE:
- // Calculates how many prime numbers are there between
- // 1 and n using multythreading.
- //---------------------------------------------
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
- #include <stdlib.h>
- void *calc_prime(void *nd);
- #define NUM_THREADS 1000
- int main() {
- char input[200];
- pthread_t threads[NUM_THREADS];
- int tr_index = 0;
- while(1) {
- scanf("%s",input);
- if(strcmp(input, "e") == 0) {
- for(int t = 0;t < tr_index;t++) {
- pthread_join(threads[t], NULL);
- }
- break;
- } else if(strcmp(input, "p") == 0) {
- int n;
- scanf("%d",&n);
- int rc = pthread_create(&threads[tr_index], NULL, calc_prime, (void*)n);
- tr_index++;
- } else {
- printf("Supported commands:\np N - Starts a new calculation for the number of primes from 1 to N\ne - Waits for all calculations to finish and exits\n");
- }
- }
- }
- //--------------------------------------------
- // FUNCTION: calc_prime
- // Calculates how many prime numbers are there between 1 and num
- // PARAMETERS:
- // num - the number to which we calculate
- //----------------------------------------------
- void *calc_prime(void *num) {
- int n = (int)num;
- printf("Prime calculation started for N=%d\n",n);
- int prime_counter = 0;
- int is_prime = 1;
- for(int i = 2;i < n;i++) {
- for(int j = 2;j < i;j++) {
- is_prime = 1;
- if(i % j == 0) {
- is_prime = 0;
- break;
- }
- }
- if(is_prime) {
- prime_counter++;
- }
- }
- printf("Number of primes for N=%d is %d\n",n,prime_counter);
- pthread_exit(NULL);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement