[Prev] [Contents] [Next]

pthread_mutex_trylock()--Lock Mutex with No Wait

Syntax

#include <pthread.h>
int pthread_mutex_trylock(pthread_mutex_t *mutex);
Threadsafe: Yes
Signal Safe: Yes

The pthread_mutex_trylock() function attempts to acquire ownership of the mutex specified without blocking the calling thread. If the mutex is currently locked by another thread, the call to pthread_mutex_trylock() will return EBUSY.

A failure of EDEADLK indicates that the mutex is already held by the calling thread.

Note that mutex initialization using the PTHREAD_MUTEX_INITIALIZER does not immediately initialize the mutex. Instead, on first use, pthread_mutex_timedlock_np() or pthread_mutex_lock() or pthread_mutex_trylock() branches into a slow path and causes the initialization of the mutex. Because a mutex isn't just a simple memory object, and requires that some resources be allocated by the system, an attempt to call pthread_mutex_destroy() or pthread_mutex_unlock() on a mutex that has was statically initialized using PTHREAD_MUTEX_INITIALER and was not yet locked will result in an EINVAL error.

The maximum number of recursive locks by the owning thread is 32,767. After which, attempts to lock the mutex will return the ERECURSE error.

Mutex Types

A normal mutex cannot be locked repeatedly by the owner. Attempts by a thread to relock an already held mutex, or to lock a mutex that was held by another thread when that thread terminated result in a deadlock condition.

A recursive mutex can be locked repeatedly by the owner. The mutex doesn't become unlocked until the owner has called pthread_mutex_unlock() for each successful lock request that it has outstanding on the mutex.

An errorcheck mutex checks for deadlock conditions that occur when a thread re-locks an already held mutex. If a thread attempts to relock a mutex that it already holds, the lock request fails with the EDEADLK error

An ownerterm mutex is an OS/400 extension to the errorcheck mutex type. An ownerterm mutex checks for deadlock conditions that occur when a thread re-locks an already held mutex. If a thread attempts to relock a mutex that it already holds, the lock request fails with the EDEADLK error. An ownerterm mutex also checks for deadlock conditions that occur when a thread attempts to lock a mutex that was held by another thread when that thread terminated (an orphaned mutex). If a thread attempts to lock an orphaned mutex, the lock request fails with the EOWNERTERM error.

When a thread terminates holding a mutex lock on a normal or errorcheck mutex, other threads that wait for that mutex will block forever. The pthreads run-time simulates the deadlock that has occurred in your application. When attempting to debug these deadlock scenarios, the CL command WRKJOB, option 20 will show the thread as in a condition wait. Displaying the call stack will show that the function deadlockedOnOrphanedMutex is in the call stack.

When a thread attempts to acquire a normal mutex that it already holds, the thread will block forever. The pthreads run-time simulates the deadlock that has occurred in your application. When attempting to debug these deadlock scenarios, the CL command WRKJOB, option 20 will show the thread as in a condition wait. Displaying the call stack will show that the function deadlockedOnAlreadyLockedMutex is in the call stack.

In order to change these behaviors, use an errorcheck or ownerterm mutex type.

Parameters

mutex
(Input) Address of the mutex to lock

Authorities and Locks

None.

Return Value

0
pthread_mutex_trylock() was successful.
value
pthread_mutex_trylock() was not successful. value is set to indicate the error condition.

Error Conditions

If pthread_mutex_trylock() was not successful, the error condition returned usually indicates one of the following errors. Under some conditions, the value returned could indicate an error other than those listed here.

[EINVAL]
The value specified for the argument is not correct.
[EBUSY]
The mutex is currently locked by another thread.
A thread terminated holding the mutex, and the mutex is an ownerterm mutex type.
A thread attempted to relock an already held mutex, and the mutex is an errorcheck mutex type.
[ERECURSE]
The recursive mutex cannot be recursively locked again.

Related Information

Example

#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include "check.h"

/*
  This example simulates a number of threads working on a parallel
  problem. The threads use pthread_mutex_trylock() so that
  they don't spend time blocking on a mutex and instead spend more
  of the time making progress towards the final solution. When
  trylock fails, the processing is done locally, eventually to
  be merged with the final parallel solution.

  This example should complete faster than the example for
  pthread_mutex_lock() in which threads solve the same parallel
  problem but spend more time waiting in resource contention.
  */
#define            LOOPCONSTANT     100000
#define            THREADS          10

pthread_mutex_t    mutex = PTHREAD_MUTEX_INITIALIZER;
int                i,j,k,l;

void *threadfunc(void *parm)
{
  int   loop = 0;
  int   localProcessingCompleted = 0;
  int   numberOfLocalProcessingBursts = 0;
  int   processingCompletedThisBurst = 0;
  int   rc;

  for (loop=0; loop<LOOPCONSTANT; ++loop) {
    rc = pthread_mutex_trylock(&mutex);
    if (rc == EBUSY) {
      /* Process continue processing the part of the problem  */
      /* that we can without the lock. We don't want to waste */
      /* time blocking. Instead, we'll count locally.         */
      ++localProcessingCompleted;
      ++numberOfLocalProcessingBursts;
      continue;
    }
    /* We acquired the lock, so this part of the can be global*/
    checkResults("pthread_mutex_trylock()\n", rc);
    /* Processing completed consist of last local processing  */
    /* plus the 1 unit of processing this time through        */
    processingCompletedThisBurst = 1 + localProcessingCompleted;
    localProcessingCompleted = 0;
    i+=processingCompletedThisBurst; j+=processingCompletedThisBurst;
    k+=processingCompletedThisBurst; l+=processingCompletedThisBurst;
    
    rc = pthread_mutex_unlock(&mutex);
    checkResults("pthread_mutex_unlock()\n", rc);
  }
  /* If any local processing remains, merge it with the global*/
  /* problem so our part of the solution is accounted for     */
  if (localProcessingCompleted) {
    rc = pthread_mutex_lock(&mutex);
    checkResults("final pthread_mutex_lock()\n", rc);
    
    i+=localProcessingCompleted; j+=localProcessingCompleted;
    k+=localProcessingCompleted; l+=localProcessingCompleted;
    
    rc = pthread_mutex_unlock(&mutex);
    checkResults("final pthread_mutex_unlock()\n", rc);
  }
  printf("Thread processed about %d%% of the problem locally\n",
         (numberOfLocalProcessingBursts * 100) / LOOPCONSTANT);
  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t             threadid[THREADS];
  int                   rc=0;
  int                   loop=0;
  pthread_attr_t        pta;

  printf("Entering testcase\n");

  pthread_attr_init(&pta);
  pthread_attr_setdetachstate(&pta, PTHREAD_CREATE_JOINABLE);
  
  printf("Creating %d threads\n", THREADS);
  for (loop=0; loop<THREADS; ++loop) {
    rc = pthread_create(&threadid[loop], &pta, threadfunc, NULL);
    checkResults("pthread_create()\n", rc);
  }

  printf("Wait for results\n");
  for (loop=0; loop<THREADS; ++loop) {
    rc = pthread_join(threadid[loop], NULL);
    checkResults("pthread_join()\n", rc);
  }  

  printf("Cleanup and show results\n");
  pthread_attr_destroy(&pta);
  pthread_mutex_destroy(&mutex);
  
  printf("\nUsing %d threads and LOOPCONSTANT = %d\n",
         THREADS, LOOPCONSTANT);
  printf("Values are: (should be %d)\n", THREADS * LOOPCONSTANT);
  printf("  ==>%d, %d, %d, %d\n", i, j, k, l);
         
  printf("Main completed\n");
  return 0;
}
Output

Entering testcase
Creating 10 threads
Wait for results
Thread processed about 100% of the problem locally
Thread processed about 90% of the problem locally
Thread processed about 88% of the problem locally
Thread processed about 94% of the problem locally
Thread processed about 93% of the problem locally
Thread processed about 96% of the problem locally
Thread processed about 90% of the problem locally
Thread processed about 91% of the problem locally
Thread processed about 81% of the problem locally
Thread processed about 76% of the problem locally
Cleanup and show results

Using 10 threads and LOOPCONSTANT = 100000
Values are: (should be 1000000)
  ==>1000000, 1000000, 1000000, 1000000
Main completed


[Prev] [Contents] [Next]
Copyright © 1998, IBM Corporation. All rights reserved.
Comments? Contact
rchthrds@us.ibm.com