user3289221
user3289221

Reputation: 3

measure elapsed time in c++ multithreaded program

I have a AI Minimax code for the game of checkers in C++. In this, the main program calls the function that I have written in a new thread while it sleeps for 5 secs after which it returns to main program

int flag = 0 ;
void execute(){
    hThread = ( HANDLE ) _beginthread( myfunction ) ;
    sleep( 5000 );

    if(flag == 1) // Do some work 
}


Outputval myfunction(...) {

   clock_t start = clock() ;
   while( double(clock() - start)/CLOCKS_PER_SEC < 4 ) {   //CLOCKS_PER_SEC = 1000

      //DO SOME WORK

   }
   flag = 1;
   return somevalue ;

}

My problem is that although the work done in my function require approximately 3-4 sec , yet the time elapsed that is calculated after every iteration is that of order 0-1 sec. So the loop in myfunction keeps on running even if 4 secs has passed and the flag is not set I have also used time() function - it gives same problem.

Upvotes: 0

Views: 986

Answers (1)

CouchDeveloper
CouchDeveloper

Reputation: 19184

Not an answer, but a "caution":

Assuming your variable flag is global and visible in both threads. Since at least one access is not atomic (C++11) or flag is not volatile (C++03), your code contains a "data race", and this will trigger "undefined behavior". Undefined behavior opens a wide range of optimization opportunities for the compiler:

The compiler will optimize your code as follows:

starting with:

int flag = 0 ;
void execute{
    hThread = ( HANDLE ) _beginthread( myfunction ) ;
    sleep( 5000 );

    if(flag == 1) // Do some work 
}

it may eventually create this code:

constexpr int flag = 0 ;
void execute{
    hThread = ( HANDLE ) _beginthread( myfunction ) ;
    sleep( 5000 );

    if(0) {}// Never do anything
}

Your code has other issues as well. I suggest a complete redesign.

Upvotes: 1

Related Questions