tags:

views:

254

answers:

3
void wait(int timeInMs)
{
    struct timespec timeToWait;
    timeToWait.tv_sec = 5;
    timeToWait.tv_nsec = timeInMs*1000;

    int rt;

    pthread_mutex_lock(&fakeMutex);
    rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
    pthread_mutex_unlock(&fakeMutex);
}

I'm using this code to try to get a thread to wait around for a bit, but it doesn't work at all. No errors, it just doesn't make the program execute any slower. Does anyone have any ideas? I been having problems finding good documentation on this.

I was thinking maybe each thread needs to have it's own condition and mutex, but that really doesn't make sense to me...

+3  A: 

That code doesn't sleep, it checks a condition for a while. As you are not probably setting cond ok it just returns immediately.

If you are not willing to synchronize threads around a signal then pthread_cond _wait is not what you need. Check here how condition variables work.

if you want to sleep with seconds precision use sleep

If you want to sleep with microseconds precision use select with timevals.

Arkaitz Jimenez
but sleep stops an entire process, I need the thread to wait.
Ciph3rzer0
sleep stops only your thread.
Arkaitz Jimenez
Use "select" with a timeval and NULL for the read, write, exception parameters. Note that using select this way only works on linux, in windows select returns immediately if only a timeval parameter is provided
laura
+1  A: 

Considering you are using timespec, and your goal isn't to synchronize but to wait I'd suggest nanosleep.

#include <time.h>

.
.
.

  struct timespec remain;
  remain.tv_sec = 5;
  remain.tv_nsec = timeInMs * 1000;

  do {
    if ( nanosleep( &remain, &remain ) == 0 || errno != EINTR ) {
      break;
    }
  } while ( 1 );

.
.
.
Tom
+1  A: 

Using any variant of sleep, the behaviour 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 the pthread_cond_timedwait... Just the way u had used was not rite... Chek the code below

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*1000ULL+timeInMs)1000ULL;

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.

Furquan