I wrote this piece of code
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
unsigned int cnt=0; /*Count variable%*/
const int NITERS=1000;
void count()
{
int i=0;
for(i=0; i<NITERS; i++)
{
cnt++;
}
pthread_exit(0);
}
int main()
{
pthread_t tid1,tid2;
/* create threads 1 and 2 */
pthread_create(&tid1,NULL,count,NULL);
pthread_create(&tid2,NULL,count,NULL);
/* Main block now waits for both threads to terminate, before it exits
If main block exits, both threads exit, even if the threads have not
finished their work */
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
if(cnt!=(unsigned)NITERS*2)
{
printf("BOOM! cnt=%d, it should be %d\n",cnt,NITERS*2);
}
else
{
printf("OK! cnt=%d\n",cnt);
}
exit(0);
}
and it exhibits this result.

Some time it get cnt to be 2000 but most of the time it is giving the result less than 2000. Can you please explain why is it happening or what is the reason behind this? How to fix it. Your answers and reasons will be sure of great help.
unsigned int cnt=0;is share-able among the threads and operation++is not atomically increasecnt. Two thread may read same values ofcntand increase, and overwritescnt. You need to apply some concurrency control mechanism like semaphore, or mutex.If you would disassemble code using following command (suppose code name is
thread1.c)The output assembly code name is
thread1.s.your wil find
cnt++is more then one instruction in low level in your code:(1)
cntfist move to%eax(2) then add one to
%exc(3) move
%eaxintocntbackAnd due to thread context switching in between this line, same value of
cntis read by more than one threads. hencecnt++is not atomic.Note: Global variable are thread shareable like
cnt, and local variable likeithat you declared incount()is thread specific.I modified your code and imposed concurrency control using semaphore, now it would work fine.
Only modified code shown
This will work good! some examples: