1

I wanted to know how to get the result like: Number x is prime or Number x is not prime, sure this threaded ex. in 10 parts. How to pass argument 3 if we have an array and how the function checks an array if is prime or not? How can I do that? Thanks in advance...I'm a beginner so sorry for any mistakes that I did in the code Code:

#include <stdio.h>
#include ...
//defining global variables
#define ARRAYSIZE 1000000
#define MAXTHREAD 10
int arr[ARRAYSIZE];
//since we split array in parts,we need a variable to reprensent a part of array
int part=0;

//Function to fill the array with values
void fill_array(int arr[],int size){...}

//Function to check if a numer is prime or not
int prime(long int num){
     //return 0:not prime
     //return 1:prime
  //Function to deside,if a element of the array is prime or not(threaded)
void* prime_threaded(void *vargp){
        //casting a void pointer to integer
        int num=*((int *)vargp);
        int thread_part=part++;
        int start=thread_part*(ARRAYSIZE/MAXTHREAD);
        int end=(thread_part +1)*(ARRAYSIZE/MAXTHREAD);
        printf("Thread works in segment %d\n",part);

        int* returnvalue = (int*) malloc(sizeof(int));
        for(int i=start;i<end;i++){
                if(prime(num==0)){
                        *returnvalue=0;
                        return returnvalue;
                }}
        *returnvalue=1;
        return returnvalue;}    
int main(){
        fill_array(arr,ARRAYSIZE);
        pthread_t threads[MAXTHREAD];

        for(int i=0;i<MAXTHREAD;i++){
                pthread_create(&threads[i],NULL,prime_threaded,(void*)arr);
        }
        for(int i = 0; i < MAXTHREAD; i++) {
                void * exit_status_thread;
                pthread_join(threads[i], &exit_status_thread);
                int result = *(int *) exit_status_thread;
                free(exit_status_thread);
        if(result==0){
                printf("\n the number is not prime\n ");
        }else{
                printf("\n the number is prime\n");
                }
        }

return 0;
}
Artani
  • 81
  • 1
  • 6
  • The idea is to have one million numbers and to divide the array in 10 parts and each part to check if the number is prime or not. – Artani May 04 '22 at 20:12
  • `int thread_part=part++;` has a race condition. Try: `int thread_part = atomic_fetch_add(&part,1);` – Craig Estey May 04 '22 at 21:18
  • `int num=*((int *)vargp);` -- `vargp` is equivalently `arr`; why are you taking the first element at this address? `if(prime(num==0))` is surely not the condition you want? Maybe `if (!prime(arr[i]))`? In any case, please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example), something we can at least attempt to compile (not this pseudocode). There are several syntax errors. – Oka May 05 '22 at 01:19

0 Answers0