Question

In: Computer Science

Write a C code to let the main thread create N child threads, where each created...

Write a C code to let the main thread create N child threads, where each created thread will randomly generate an integer between 0 to 10 and put it into a global array variable. After that, the main thread will calculate the sum of all the generated integers. N should be input as a command line argument.

Complete the following C code by filling all “???”s in the code sketch. NOTE: when you compile the code, you need to add the parameter “-lpthread” to “gcc”, e.g., “gcc YourCode.c -lpthread”

// include the header file that allows us to use pthread
#include <???>
#include <stdio.h>
// include the header file that allows us to use dynamic memory management 
#include <???>
// define a pointer to point to an array to hold the randomly generated integers
int *a;

// define the function used to create a thread
???runner(???param);

int main(int argc, char *argv[])
{
        if (argc != 2)
        {
                fprintf(stderr, "usage: %s <integer value>\n", argv[0]);
                return -1;
        }

        int N = atoi(argv[1]);

        if (N<=0)
        {
                fprintf(stderr, "%d must be > 0\n", N);
                return -1;
        } 

        // define an array to hold the threads to be created
        ???              workers[N]; 

        // define a set of thread attributes for creating threads
???                     attr;

        // define a variable later used for “for” loop
int i;

        // use dynamic memory management to create an array to hold the integers
        a = ???                                         ;

        // seed the random number generator
        srandom((unsigned)time(NULL));

        // initialize the default thread attributes
        ???





        // use “for” loop to create the threads, where the index of the created thread in workers
// array should be passed to the thread as the parameter
        ???





        // use “for” loop to wait for all the threads to exit
        ???




        // calculate the sum
        int sum = 0;

        for (i=0; i<N; i++) sum += a[i];

        printf("sum = %d\n", sum);

        // free the dynamically created array
        ???

}

// The created thread will start its execution from this function
???             runner(???              param)
{
        // get the index of the thread in workers array and put it to “thread_index”
        int thread_index = ???                          ;       

        // randomly generate an integer between 0 to 10
        a[thread_index] = random()%11;  

        // print the information on the screen
        printf("Thread %d generates integer %d ...\n", thread_index, a[thread_index]);

        // terminate the thread
        ???



}

Solutions

Expert Solution

#include <pthread.h>
#include <stdio.h>
// include the header file that allows us to use dynamic memory management
#include <stdlib.h>
// define a pointer to point to an array to hold the randomly generated integers
int *a;

// define the function used to create a thread
void * runner(void* param);

int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "usage: %s <integer value>\n", argv[0]);
return -1;
}

int N = atoi(argv[1]);

if (N <= 0)
{
fprintf(stderr, "%d must be > 0\n", N);
return -1;
}

// define an array to hold the threads to be created
pthread_t workers[N];
  
void* rval;

// define a set of thread attributes for creating threads
pthread_attr_t attr;

// define a variable later used for “for” loop
int i;

// use dynamic memory management to create an array to hold the integers
a = (int*)calloc(N, sizeof(int)); ;

// seed the random number generator
srandom((unsigned)time(NULL));

// initialize the default thread attributes
pthread_attr_init(&attr);


// use “for” loop to create the threads, where the index of the created thread in workers
// array should be passed to the thread as the parameter
for(i=0;i<N;i++) {
pthread_create(&workers[i],&attr,runner,i);
}

// use “for” loop to wait for all the threads to exit
for(i = 0; i < N; i++)
pthread_join(workers[i],&rval);

// calculate the sum
int sum = 0;

for (i=0; i<N; i++) sum += a[i];

printf("sum = %d\n", sum);

// free the dynamically created array
free(a);

}

// The created thread will start its execution from this function
void* runner(void* param)
{
// get the index of the thread in workers array and put it to “thread_index”
int thread_index = (int *)param; ;   

// randomly generate an integer between 0 to 10
a[thread_index] = random()%11;

// print the information on the screen
printf("Thread %d generates integer %d ...\n", thread_index, a[thread_index]);

// terminate the thread
pthread_exit(NULL);
}

OUTPUT :

For N = 10


Related Solutions

Thread Programming (C Programming) Objective Develop threads: thread and main. Functionality of Threads: The main program...
Thread Programming (C Programming) Objective Develop threads: thread and main. Functionality of Threads: The main program accepts inputs from the user from the console. The user can provide the following two types of input: add num1 num2 mult num1 num2 Here, num1 and num2 are two integer numbers. E.g., the user may input add 1 2. The threads receive the command along with the number, and performs the appropriate arithmetic operation and returns the results to main program. The main...
Write a C program that creates 5 threads sends the thread index as an argument to...
Write a C program that creates 5 threads sends the thread index as an argument to the thread execution procedure/function. Also, the main process/thread joins the newly created threads sequentially one after the other. From the thread procedure print “I am a thread and my index is “ [print the correct index number]. From the main thread after the join print “I am the main thread and just completed joining thread index “ [print the correct index].
You will create a number of threads—for example, 100—and each thread will request a pid, sleep...
You will create a number of threads—for example, 100—and each thread will request a pid, sleep for a random period of time, and then release the pid. (Sleeping for a random period of time approximates the typical pid usage in which a pid is assigned to a new process, the process executes and then terminates, and the pid is released on the process's termination.) On UNIX and Linux systems, sleeping is accomplished through the sleep() function, which is passed an...
write C program to create 4 threads for summing the numbers between 1 and 40 where...
write C program to create 4 threads for summing the numbers between 1 and 40 where the first thread computes the sum between 1 and 10; the second thread computes the sum between 11 and 20; the third thread computes the sum between 21 and 30; and the fourth thread compute the sum between 31 and 40. The output should be similar to the following. The sum from 1 to 10 = 55 The sum from 11 to 20 =...
Write a recursive function to implement the Factorial of n (n!). In the main, let the...
Write a recursive function to implement the Factorial of n (n!). In the main, let the user input a positive integer and call your function to return the result.
Write code in your “main” function that performs the following: a) For each n є {10^3,...
Write code in your “main” function that performs the following: a) For each n є {10^3, 5x10^3, 10^4, 5x10^4, 10^5}, randomly generate 5 integer arrays of length n. b) Run each of the five comparison sorts you implemented in Step 1 on all the five arrays generated in Step 2.a and record the worst-case actual running time and number of comparisons performed among elements in the input array. #include<iostream> #include<cmath> using namespace std; void displayArray(int a[], int n) { cout<<"\nArray...
DO THIS IN JAVA Write a complete Java program. the program has two threads. One thread...
DO THIS IN JAVA Write a complete Java program. the program has two threads. One thread prints all capital letters 'A' to'Z'. The other thread prints all odd numbers from 1 to 21.
Write a C++ program where you implement a synchronized multithreaded version of HAPPY with four threads....
Write a C++ program where you implement a synchronized multithreaded version of HAPPY with four threads. The program will take in an array from 1 to n (n = 50) and will be passed to four different threads: If the current number is divisible by 2, then print HAP If the current number is divisible by 5, then print PY If the current number is divisible by both 2 and 5, then print HAPPY If the number is neither divisible...
Write the code in C++. Write a program to implement Employee Directory. The main purpose of...
Write the code in C++. Write a program to implement Employee Directory. The main purpose of the class is to get the data, store it into a file, perform some operations and display data. For the purpose mentioned above, you should write a template class Directory for storing the data empID(template), empFirstName(string), empLastName(string), empContactNumber(string) and empAddress(string) of each Employee in a file EmployeeDirectory.txt. 1. Write a function Add to write the above mentioned contact details of the employee into EmployeeDirectory.txt....
Write a factorial C++ program where n=10,000,000
Write a factorial C++ program where n=10,000,000
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT