Name

pthread_mutex_timedlock
- lock a mutex without blocking indefinitely

Library

libpthread.lib

Synopsis

  #include <pthread.h>
  #include <time.h>
  int pthread_mutex_timedlock (pthread_mutex_t *mutex, const struct timespec *abstime);

Return values

If successful, pthread_mutex_timedlock will return zero, otherwise an error number will be returned to indicate the error.

Detailed description

The pthread_mutex_timedlock function will lock mutex. If it is already locked the calling thread will block until the mutex becomes available or the timeout, specified by abstime, expires. The time of the timeout is an absolute time and is not relative to the current time.

Examples

#include <sys/time.h>
#define TIMEOUT 3    
/* 3 seconds of timeout time for  pthread_mutex_timedlock(). */
struct timespec timeout;
struct timeval currsec1;
int rc;
pthread_mutex_t  mutex;

         

/* Get the current time before the mutex locked. */
gettimeofday(&currsec1, NULL);
/* Absolute time, not relative. */
timeout.tv_sec = currsec1.tv_sec + TIMEOUT;
timeout.tv_nsec = currsec1.tv_usec * 1000;
printf("Timed mutex lock will block for %d seconds starting from: %ld.%06ld\n", TIMEOUT, (long)currsec1.tv_sec, (long)currsec1.tv_usec);
rc = pthread_mutex_timedlock(&mutex, &timeout);
if(rc != 0) {
  if (rc == ETIMEDOUT) {
   fprintf(stderr,"Thread stops waiting when time is out\n");
  }
  else {
   fprintf(stderr,"pthread_mutex_timedwait return %d\n", rc);
  }
}
fprintf(stderr,"Thread wakened up\n");

         

Errors

The pthread_mutex_timedlock function will fail if:
[EINVAL]
  The mutex was created with the protocol attribute having the value PTHREAD_PRIO_PROTECT and the calling thread’s priority is higher than the mutex’s current priority ceiling.
[EINVAL]
  The process or thread would have blocked, and abs_timeout specified a nanosecond value less than zero or greater than or equal to 1 billion.
[EINVAL]
  The mutex parameter is invalid.
[ETIMEDOUT]
  The mutex could not be locked before the timeout expired.
[ENOSYS]
  If locking is not supported for this mutex kind.
[EDEADLK]
  The current thread already owns the mutex.

See also

pthread_mutex_destroy, pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock

Feedback

For additional information or queries on this page send feedback

© 2008-2009 Nokia Corporation. All rights reserved. This documentation can be used in the connection with this Product to help and support the user.

Top