I want to simulate a theater reservation system where customers communicate with operators to reserve seats in C. I am using the pthread library. When the thread is created, it tries to acquire the mutex of the variable that holds the number of available operators and checks to see whether any operator is available(with the use of a condition variable) and if not, the thread goes to sleep. I want to know the time it took for the thread to connect with an operator i.e. the time it took for the thread to get past the condition variable. Can I just use a timer at the start of the thread and right after the condition variable or this wouldn't work because when the thread is blocked the timer is blocked too? If this is the case, what is the correct way to do this? Thanks.
void* thread_transaction(void* arg) //the function passed to
pthread_create
{
//instantiating variables and such...
//reserving an operator
pthread_mutex_lock(&tel_mut);
while(threadData->available_tel <= 0)
pthread_cond_wait(&tel_cond, &tel_mut);
//can I put a timer at the start and right here and accurately
//measure the time?
Assuming you are writing for a Posix-compatible system (like Linux), you can use clock_gettime()
before and after the wait loop, and subtract the start time from the end time to get the elapsed time. You'll want to use a wall-time clock, not a CPU-time clock. Since this function places its result in a struct timespec
, which is a two-part value, the subtraction is not trivial (but neither is it particularly complicated): you need to consider the case where subtracting the nanosecond fields results in a negative number.
The difference between the CLOCK_REALTIME
and CLOCK_MONOTONIC
is that the monotonic clock is not affected by adjustments to the host's clock required to synchronise with a time service. (Another difference is that there is no information about the what the value returned by CLOCK_MONOTONIC
represents in terms of the calendar, since it usually starts counting at system boot. However, the difference between two times is completely meaningful.)