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

70.2K

Verified Solution

Question

Programming

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

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

// include the header file that allows us to use pthread#include #include // 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 integersint *a;// define the function used to create a thread???runner(???param);int main(int argc, char *argv[]){    if (argc != 2)    {        fprintf(stderr, \"usage: %s \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” loopint 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

Answer & Explanation Solved by verified expert
3.7 Ratings (317 Votes)
include include include the header file that allows us to use    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students