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

The code below is supposed to do the following: create 100 threads, have each cr

ID: 3763991 • Letter: T

Question

The code below is supposed to do the following: create 100 threads, have each created thread compute a square of a number from 0 to 99, the result, and exit. The main thread waits for all threads to exit and then exits itself. Does the code below correctly accomplish the task? Explain why or why not.

#include <pthread.h>
#include <stdio.h>

void* computeSquare(void* arg)
{
          int number = arg;
         
          printf("The square is: %d ", number * number);
}

int main()
{
            pthread_t tids[100];

             for(int i = 0; i < 100; ++i)
             {
                              pthread_create(&tids[i], NULL, computeSquare, i);
             }

             for(int i = 0; i < 100; ++i)
             {
                       pthread_join(tids[i], NULL);
             }
             
            return 0;
}

Explanation / Answer

Yes this code do works correctly. But there is no guarantee that the threads will be executed in that order, which means the output may not be printed in the order from 0 - 99. Otherthan that everything works perfect. The first loops creates a total of 100 threads. And the second loop joins the threads. If you have any further queries, just get back to me.