void wait(int timeInMs)
{
struct timespec timeToWait;
timeToWait.tv_sec = 5;
timeToWait.tv_nsec = timeInMs*1000;
int rt;
pthread_mutex_lock(&am
Using any variant of sleep, the behavior is not guaranteed. All the threads can also sleep since the kernel is not aware of the different threads.
A safer and cleaner solution to use is pthread_cond_timedwait. You used the API incorrectly. Here is a better example:
pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;
void mywait(int timeInMs)
{
struct timespec timeToWait;
struct timeval now;
int rt;
gettimeofday(&now,NULL);
timeToWait.tv_sec = now.tv_sec+5;
timeToWait.tv_nsec = (now.tv_usec+1000UL*timeInMs)*1000UL;
pthread_mutex_lock(&fakeMutex);
rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
pthread_mutex_unlock(&fakeMutex);
printf("\nDone\n");
}
void* fun(void* arg)
{
printf("\nIn thread\n");
mywait(1000);
}
int main()
{
pthread_t thread;
void *ret;
pthread_create(&thread, NULL, fun, NULL);
pthread_join(thread,&ret);
}
You need to specify how much time to wait from current time. Since you were only telling 5 sec and some nano-seconds it found that the time had already passed and did not wait...Please let me know if any more doubts.