In: Computer Science
1. What does the following program do?
2. What output does the program produce?
3. Examine the program code carefully. Is the program functioning correctly?
4. If you do not think the program is working correctly, describe why?
5. Include one screenshot of the program's output.
C++ PROGRAM:
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
int count;
void* myFunction(void* arg)
{
int actual_arg = *((int*) arg);
for(unsigned int i = 0; i < 10; ++i) {
count++;
std::cout << "Thread #" << actual_arg << " count
= " << count << std::endl;
// Random wait - This code is just to ensure that the threads
// show data sharing problems
int max = rand() % 100000;
for (int x = 0; x < max; x++);
// End of random wait code
}
pthread_exit(NULL);
}
int main()
{
int rc[2];
pthread_t ids[2];
int args[2];
count = 0;
for(unsigned int i = 0; i < 2; ++i) {
args[i] = i;
rc[i] = pthread_create(&ids[i], NULL, myFunction, (void*)
&args[i]);
}
for(unsigned int i = 0; i < 2; ++i) {
pthread_join(ids[i], NULL);
}
std::cout << "Final count = " << count <<
std::endl;
pthread_exit(NULL);
}
Firstly, following are the steps to compile-and-run :
1.
The program attempts to increment the global-variable count in multiple threads :
2.
The program produces the state of global variable count, as and when it is incremented by a thread.
3.
Spuriously, the final value of count does not come out to be 20.
So, the program is not 100% resilient.
4.
The reason is that there is no mutual-exclusion between threads, when the shared global-variable count is modified/incremented.
Thus, count may not be incremented as expected, due to random context-switches while the variable-modification is in progress.
5.
Following is a screenshot, when the program updated count to 19 (as against expected value of 20) :