Programming Language: C Programming Environment: PuTTy Write a program, thrIncr,
ID: 3849365 • Letter: P
Question
Programming Language: C
Programming Environment: PuTTy
Write a program, thrIncr, that creates two threads, each of which executes the same function. The function, threadFunc(), executes a loop that repeatedly increments a global variable, counter, by copying counter into the local variable, loc, incrementing loc, and copying loc back to counter. (Since loc is an automatic variable allocated on the pthread stack, each thread has its own copy of this variable.) The number of iterations of the loop is determined by the command-line argument supplied to the program, or by a default value (10,000,000) if no argument is supplied.
Run the program first by specifying the value 1000 as the number of iterations of the loop. Capture the output. The second run of the program uses the default value for the number of iterations of the loop. Capture the output. Do the outputs in both the runs look correct?
To avoid the problems that can occur when threads try to update a shared variable, we must use a mutex to ensure that only one thread at a time can access the variable. Modify the program to protect the critical section by a mutex. Run the program twice again as before, first by using a value of 1000 for the number of iterations and then by using the default value. Capture both outputs. What changes in the outputs do you see after using the mutex?
Explanation / Answer
void ThreadFunc(DWORD n)
{
int i,j;
for (i=0;i<10;i++)
{
for (j=0;j<30;j++)
{
cout << n ;
// Sleep(10*n);
}
cout << endl ;}
}
void main(void)
{
HANDLE hThrds[5];
DWORD threadId;
int i;
//Create 5 threads reusing
for (i=0; i<5; i++)
{
hThrds[i] = CreateThread(0,0,
(LPTHREAD_START_ROUTINE) ThreadFunc,
(LPVOID)i,
0,
&threadId );
if (hThrds[i])
{
cout << "Thread launched" << i<< endl;
}
}
// Wait for the threads to complete by putting base thread to sleep.
// We'll see a better way of doing this later.
WaitForMultipleObjects(5, hThrds,
TRUE, INFINITE);
for (i=0; i<5; i++)
{
CloseHandle(hThrds[i]);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.