OpenMAXBellagio 0.9.3
tsemaphore.c
Go to the documentation of this file.
00001 
00027 #include <pthread.h>
00028 #include <sys/time.h>
00029 #include <errno.h>
00030 #include "tsemaphore.h"
00031 #include "omx_comp_debug_levels.h"
00032 
00039 OSCL_EXPORT_REF int tsem_init(tsem_t* tsem, unsigned int val) {
00040     int i;
00041     i = pthread_cond_init(&tsem->condition, NULL);
00042     if (i!=0) {
00043         return -1;
00044     }
00045     i = pthread_mutex_init(&tsem->mutex, NULL);
00046     if (i!=0) {
00047         return -1;
00048     }
00049     tsem->semval = val;
00050     return 0;
00051 }
00052 
00057 OSCL_EXPORT_REF void tsem_deinit(tsem_t* tsem) {
00058   pthread_cond_destroy(&tsem->condition);
00059   pthread_mutex_destroy(&tsem->mutex);
00060 }
00061 
00069 OSCL_EXPORT_REF int tsem_timed_down(tsem_t* tsem, unsigned int milliSecondsDelay) {
00070     int err = 0;
00071     struct timespec final_time;
00072     struct timeval currentTime;
00073     long int microdelay;
00074 
00075     gettimeofday(&currentTime, NULL);
00077     microdelay = ((milliSecondsDelay * 1000 + currentTime.tv_usec));
00078     final_time.tv_sec = currentTime.tv_sec + (microdelay / 1000000);
00079     final_time.tv_nsec = (microdelay % 1000000) * 1000;
00080     pthread_mutex_lock(&tsem->mutex);
00081     while (tsem->semval == 0) {
00082         err = pthread_cond_timedwait(&tsem->condition, &tsem->mutex, &final_time);
00083         if (err != 0) {
00084             tsem->semval--;
00085         }
00086     }
00087     tsem->semval--;
00088     pthread_mutex_unlock(&tsem->mutex);
00089     return err;
00090 }
00091 
00097 OSCL_EXPORT_REF void tsem_down(tsem_t* tsem) {
00098   pthread_mutex_lock(&tsem->mutex);
00099   while (tsem->semval == 0) {
00100     pthread_cond_wait(&tsem->condition, &tsem->mutex);
00101   }
00102   tsem->semval--;
00103   pthread_mutex_unlock(&tsem->mutex);
00104 }
00105 
00110 OSCL_EXPORT_REF void tsem_up(tsem_t* tsem) {
00111   pthread_mutex_lock(&tsem->mutex);
00112   tsem->semval++;
00113   pthread_cond_signal(&tsem->condition);
00114   pthread_mutex_unlock(&tsem->mutex);
00115 }
00116 
00121 OSCL_EXPORT_REF void tsem_reset(tsem_t* tsem) {
00122   pthread_mutex_lock(&tsem->mutex);
00123   tsem->semval=0;
00124   pthread_mutex_unlock(&tsem->mutex);
00125 }
00126 
00131 OSCL_EXPORT_REF void tsem_wait(tsem_t* tsem) {
00132   pthread_mutex_lock(&tsem->mutex);
00133   pthread_cond_wait(&tsem->condition, &tsem->mutex);
00134   pthread_mutex_unlock(&tsem->mutex);
00135 }
00136 
00141 OSCL_EXPORT_REF void tsem_signal(tsem_t* tsem) {
00142   pthread_mutex_lock(&tsem->mutex);
00143   pthread_cond_signal(&tsem->condition);
00144   pthread_mutex_unlock(&tsem->mutex);
00145 }
00146