Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement this in C++ using pthreads. (You\'ll have to use Cygwin or something s

ID: 3784372 • Letter: I

Question

Implement this in C++ using pthreads. (You'll have to use Cygwin or something similar if you're on Windows.)

You will have one shared variable that is modifed called sum. In each thread, check a number and add it to sum if it is a factor of N. You check to see if a number is a factor using the modulo operator. You'll need to protect access to sum using a mutex. You'll also have a shared variable N, but no threads will modify it so it doesn't need to be protected. Start with P = 1 to get things working. That way you won't have any race conditions.

You can cast an integer to a void* with the code (void*)(size t)N.

Use the following code to complete the answer.

#include
#include
#include

int N;

int main(int argc, char **argv) {
if (argc < 3) {
printf("Usage: perfect N P ");
return 1;
}
N = atoi(argv[1]);
const int P = atoi(argv[2]);

printf("N = %d, P = %d ", N, P);
}

Explanation / Answer

#include <pthread.h>

#include <stdio.h>

#include <stdlib.h>

void *worker_thread(void *arg)

{

        printf("This is worker_thread() ");

        pthread_exit(NULL);

}

int main()

{

        pthread_t my_thread;

        int ret;

        printf("In main: creating thread ");

        ret = pthread_create(&my;_thread, NULL, &worker;_thread, NULL);

        if(ret != 0) {

                printf("Error: pthread_create() failed ");

                exit(EXIT_FAILURE);

        }

        pthread_exit(NULL);

}