Friday, April 26, 2013

pthread_mutex_trylock example c c++


NAME

pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock - lock and unlock a mutex

 SYNOPSIS

#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

 DESCRIPTION

The mutex object referenced by mutex is locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread blocks until the mutex becomes available. This operation returns with the mutex object referenced by mutex in the locked state with the calling thread as its owner.If the mutex type is PTHREAD_MUTEX_NORMAL, deadlock detection is not provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behaviour results.
If the mutex type is PTHREAD_MUTEX_ERRORCHECK, then error checking is provided. If a thread attempts to relock a mutex that it has already locked, an error will be returned. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error will be returned.(pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock)
If the mutex type is PTHREAD_MUTEX_RECURSIVE, then the mutex maintains the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count is set to one. Every time a thread relocks this mutex, the lock count is incremented by one. Each time the thread unlocks the mutex, the lock count is decremented by one. When the lock count reaches zero, the mutex becomes available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error will be returned.(pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock)
If the mutex type is PTHREAD_MUTEX_DEFAULT, attempting to recursively lock the mutex results in undefined behaviour. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behaviour. Attempting to unlock the mutex if it is not locked results in undefined behaviour.
The function pthread_mutex_trylock() is identical to pthread_mutex_lock() except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call returns immediately.
The pthread_mutex_unlock() function releases the mutex object referenced by mutex. The manner in which a mutex is released is dependent upon the mutex's type attribute. If there are threads blocked on the mutex object referenced by mutex whenpthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy is used to determine which thread shall acquire the mutex. (In the case of PTHREAD_MUTEX_RECURSIVE mutexes, the mutex becomes available when the count reaches zero and the calling thread no longer has any locks on this mutex).
If a signal is delivered to a thread waiting for a mutex, upon return from the signal handler the thread resumes waiting for the mutex as if it was not interrupted.

 RETURN VALUE

If successful, the pthread_mutex_lock() and pthread_mutex_unlock() functions return zero. Otherwise, an error number is returned to indicate the error.The function pthread_mutex_trylock() returns zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error.

 ERRORS

The pthread_mutex_lock() and pthread_mutex_trylock() functions 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.
The pthread_mutex_trylock() function will fail if:
[EBUSY]
The mutex could not be acquired because it was already locked.
The pthread_mutex_lock(), pthread_mutex_trylock() and pthread_mutex_unlock() functions may fail if:
[EINVAL]
The value specified by mutex does not refer to an initialised mutex object.
[EAGAIN]
The mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded.
The pthread_mutex_lock() function may fail if:
[EDEADLK]
The current thread already owns the mutex.
The pthread_mutex_unlock() function may fail if:
[EPERM]
The current thread does not own the mutex.
These functions will not return an error code of [EINTR].

 EXAMPLES of (pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock)

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
#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 do not 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 do not 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