Question: #include #include #include #include #define NITER 1000000 int cnt = 0; void * Count(void * a) { int i, tmp; for(i = 0; i <

#include
#include
#include
#include
#define NITER 1000000
int cnt = 0;
void * Count(void * a)
{
int i, tmp;
for(i = 0; i < NITER; i++)
{
tmp = cnt; /* copy the global cnt locally */
tmp = tmp+1; /* increment the local copy */
cnt = tmp; /* store the local value into the global cnt */
}
}
int main(int argc, char * argv[])
{
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, Count, NULL))
{
printf(" ERROR creating thread 1");
exit(1);
}
if(pthread_create(&tid2, NULL, Count, NULL))
{
printf(" ERROR creating thread 2");
exit(1);
}
if(pthread_join(tid1, NULL)) /* wait for the thread 1 to finish */
{
printf(" ERROR joining thread");
exit(1);
}
if(pthread_join(tid2, NULL)) /* wait for the thread 2 to finish */
{
printf(" ERROR joining thread");
exit(1);
}
if (cnt < 2 * NITER)
printf(" BOOM! cnt is [%d], should be %d ", cnt, 2*NITER);
else
printf(" OK! cnt is [%d] ", cnt);
pthread_exit(NULL);
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!