Beispiel #1
0
bool cFUSemaphore::Down(uint32 blockTime)
{
#if defined(WIN32)
	return WaitForSingleObject(semaphoreHandle, blockTime) == WAIT_OBJECT_0;
#elif defined(FP_APPLE)
	return MPWaitOnSemaphore(semaphoreHandle, (blockTime == (uint32)-1) ? kDurationForever : blockTime) == noErr;
#elif defined(LINUX) || defined(ANDROID) || defined(IOS)
	if (blockTime == (uint32) -1)
	{
		return sem_wait(&semaphoreHandle) == 0;
	}
	else
	{
#ifdef IOS
		//f**k because I am f*****g lazy to implement this so...
		return sem_wait(&semaphoreHandle) == 0;
#else

		// The basic POSIX semaphore does not support a block time, but rather a deadline.
		timespec deadline;
		
		clock_gettime(CLOCK_REALTIME, &deadline);
		
		deadline.tv_nsec += (blockTime * 1000);
		
		return sem_timedwait(&semaphoreHandle, &deadline) == 0;
#endif
	}
#endif
}
Beispiel #2
0
static int
do_test (void)
{
  int res = 0;
  int r;
  struct timespec t = { -2, 0 };
  pthread_t pth;

  sem_init (&sem, 0, 0);
  r = sem_timedwait (&sem, &t);
  if (r != -1 || errno != ETIMEDOUT)
    {
      puts ("sem_timedwait did not fail with ETIMEDOUT");
      res = 1;
    }

  pthread_mutex_lock (&m1);
  pthread_rwlock_wrlock (&rw1);
  pthread_rwlock_rdlock (&rw2);
  pthread_mutex_lock (&m2);
  if (pthread_create (&pth, 0, th, 0) != 0)
    {
      puts ("cannot create thread");
      return 1;
    }
  r = pthread_cond_timedwait (&c, &m2, &t);
  if (r != ETIMEDOUT)
    {
      puts ("pthread_cond_timedwait did not return ETIMEDOUT");
      res = 1;
    }
  void *thres;
  pthread_join (pth, &thres);
  return res | (thres != NULL);
}
Beispiel #3
0
int DbDumperWriter::write_record(bool flush)
{
  int ret = OB_SUCCESS;
  RecordInfo * rec = NULL; 
  struct timespec timeout;
  UNUSED(flush);

  timeout.tv_sec = time(NULL) + kSemWaitTimeout;
  timeout.tv_nsec = 0;

  if (!records_.empty()) {
    CThreadGuard gard(&records_lock_);
    //no problem doing this, because only one thread is waiting on the queue
    rec = records_.front();
  } else if (running_) {
    sem_timedwait(&sem_empty_, &timeout);
  }

  if (rec != NULL) {
    CThreadGuard gard(&records_lock_);

    if (file_ == NULL || (ret = file_->Append(rec->buf, rec->length)) != OB_SUCCESS) {
      TBSYS_LOG(ERROR, "Write record failed, ret:%d, path:%s, len:%d", ret, path_.c_str(), rec->length);
    } else {
      writen_lines_++;
      records_.pop_front();
      free_record(rec);
    }
  }

  return ret;
}
Beispiel #4
0
/*
 *  semaphore_posix_thrash()
 *	exercise the semaphore
 */
static void semaphore_posix_thrash(
	const char *name,
	const uint64_t max_ops,
	uint64_t *counter)
{
	do {
		int i;
		struct timespec timeout;

		if (clock_gettime(CLOCK_REALTIME, &timeout) < 0) {
			pr_fail_dbg(name, "clock_gettime");
			return;
		}
		timeout.tv_sec++;

		for (i = 0; i < 1000; i++) {
			if (sem_timedwait(&shared->sem_posix.sem, &timeout) < 0) {
				if (errno == ETIMEDOUT)
					goto timed_out;
				if (errno != EINTR)
					pr_fail_dbg(name, "sem_wait");
				break;
			}
			(*counter)++;
			if (sem_post(&shared->sem_posix.sem) < 0) {
				pr_fail_dbg(name, "sem_post");
				break;
			}
timed_out:
			if (!opt_do_run)
				break;
		}
	} while (opt_do_run && (!max_ops || *counter < max_ops));
}
Beispiel #5
0
    ///////////////////////////////////////////////////////////////////////
    ///  Function: TimedWait
    ///
    ///    Author: $author$
    ///      Date: 3/31/2012
    ///////////////////////////////////////////////////////////////////////
    virtual XosError TimedWait
    (const struct timespec& untilTime)
    {
        XosError error = XOS_ERROR_FAILED;
        int err;

        if ((m_isCreated))
        if (!(err = sem_timedwait(&m_sem, &untilTime)))
            error = XOS_ERROR_NONE;
        else
        if (ETIMEDOUT == err)
        {
            error = XOS_ERROR_TIMEDOUT;
            XOS_DBT(("() timed out on sem_timedwait()\n"));
        }
        else
        if (EINTR == err)
        {
            error = XOS_ERROR_INTERRUPTED;
            XOS_DBT(("() interrupted on sem_timedwait()\n"));
        }
        else
        {   XOS_DBE(("() failed (%d) on sem_timedwait()\n", err)); }

        return error;
    }
inline bool semaphore_timed_wait(sem_t *handle, const boost::posix_time::ptime &abs_time)
{
    if(abs_time == boost::posix_time::pos_infin) {
        semaphore_wait(handle);
        return true;
    }
#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS
    timespec tspec = ptime_to_timespec(abs_time);
    for (;;) {
        int res = sem_timedwait(handle, &tspec);
        if(res == 0)
            return true;
        if (res > 0) {
            //buggy glibc, copy the returned error code to errno
            errno = res;
        }
        if(system_error_code() == ETIMEDOUT) {
            return false;
        }
        throw interprocess_exception(system_error_code());
    }
    return false;
#else //#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS
    boost::posix_time::ptime now;
    do {
        if(semaphore_try_wait(handle))
            return true;
        thread_yield();
    } while((now = microsec_clock::universal_time()) < abs_time);
    return false;
#endif   //#ifdef BOOST_INTERPROCESS_POSIX_TIMEOUTS
}
Beispiel #7
0
/* I have an XBee controlling relays for lights. It seems to become a little deaf when a number of
   relays are on simultaneously, so I made safeTx(). safeTS() will retry the communication upto
   retryCount times... seems to do the job :)                                                       */
int safeTx(struct xbee *xbee, struct xbee_con *con, int retryCount, struct xbee_pkt **pkt, char *format, ...) {
  va_list ap;
	sem_t *sem;
	int ret;
	
	if ((sem = xbee_conGetData(xbee, con)) == NULL) {
		return 5;
	}
	
	/* send the request */
	do {
		va_start(ap, format);
		ret = xbee_convTx(xbee, con, format, ap);
		va_end(ap);
		
		if (ret != 0) {
			if (ret != 4) break;
		} else {
			/* if transmission succeeded, wait up to 5 seconds for the result (try again on timeout) */
			struct timespec to;
			clock_gettime(CLOCK_REALTIME, &to);
			to.tv_sec += 5;
			if (sem_timedwait(sem, &to)) {
				printf("Timeout...\n");
				ret = -1;
			}
		}
		usleep(1000);
	} while (ret && retryCount--);
	
	*pkt = kPkt;
	
	return ret;
}
Beispiel #8
0
bool CSem::Wait(int timeout)
{
#ifdef WIN32
	if (timeout <= 0)
	{
		timeout = INFINITE;
	}
	if (WaitForSingleObject(m_hSem, timeout) != WAIT_OBJECT_0)
	{
		return false;
	}
#else
	if (timeout <= 0)
	{
		return (sem_wait(&m_semid) == 0);
	}
	else
	{
		timespec ts;
		ts.tv_sec = time(NULL) + timeout/1000;
		ts.tv_nsec = (timeout%1000)*1000000;
		return (sem_timedwait(&m_semid, &ts) == 0);
	}
#endif
	return true;
}
Beispiel #9
0
static void *
tf (void *arg)
{
  pthread_cleanup_push (cleanup, NULL);

  int e = pthread_barrier_wait (&bar);
  if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("tf: 1st barrier_wait failed");
      exit (1);
    }

  struct timeval tv;
  (void) gettimeofday (&tv, NULL);

  struct timespec ts;
  TIMEVAL_TO_TIMESPEC (&tv, &ts);

  /* Timeout in 5 seconds.  */
  ts.tv_sec += 5;

  /* This call should block and be cancelable.  */
  sem_timedwait (&sem, &ts);

  pthread_cleanup_pop (0);

  puts ("sem_timedwait returned");

  return NULL;
}
Beispiel #10
0
EXEC_RETURN sem_Lock(SEM sem,unsigned long msec){
#if defined(WIN32) || defined(_WIN64)
	return WaitForSingleObject(sem,msec) == WAIT_OBJECT_0 ? EXEC_SUCCESS:EXEC_ERROR;
#else
    int res;
	if(!msec)
		res = sem_trywait(sem);
	else if(msec == ~0)
		res = sem_wait(sem);
	else{
#ifndef	__APPLE__
		struct timeval utc = {0};
		struct timespec time_val = {0};
		if(!gettimeofday(&utc,NULL)){
			time_val.tv_sec = utc.tv_sec + msec / 1000;
			msec %= 1000;
			time_val.tv_nsec = utc.tv_usec * 1000 + msec * 1000000;
			res = sem_timedwait(sem,&time_val);
		}
#else
		errno = EINVAL;
#endif
		res = -1;
	}
	return res == 0 ? EXEC_SUCCESS:EXEC_ERROR;
#endif
}
Beispiel #11
0
WELS_THREAD_ERROR_CODE    WelsEventWaitWithTimeOut (WELS_EVENT* event, uint32_t dwMilliseconds) {
  if (dwMilliseconds != (uint32_t) - 1) {
    return sem_wait (event);
  } else {
#if defined(MACOS)
    int32_t err = 0;
    int32_t wait_count = 0;
    do {
      err = sem_trywait (event);
      if (WELS_THREAD_ERROR_OK == err)
        break;// WELS_THREAD_ERROR_OK;
      else if (wait_count > 0)
        break;
      usleep (dwMilliseconds * 1000);
      ++ wait_count;
    } while (1);
    return err;
#else
    struct timespec ts;
    struct timeval tv;

    gettimeofday (&tv, 0);

    ts.tv_sec = tv.tv_sec + dwMilliseconds / 1000;
    ts.tv_nsec = tv.tv_usec * 1000 + (dwMilliseconds % 1000) * 1000000;

    return sem_timedwait (event, &ts);
#endif//MACOS
  }
}
Beispiel #12
0
bool uHTTP::Semaphore::wait(time_t timeoutSec) {
  if (!this->isInitialized)
    return false;
  
  bool isSuccess = true;
  
#if defined(__APPLE__)
  if (0 < timeoutSec) {
    mach_timespec_t machTimeout;
    machTimeout.tv_sec = (unsigned int)timeoutSec;
    machTimeout.tv_nsec = 0;
    isSuccess = (semaphore_timedwait(semId, machTimeout) == KERN_SUCCESS) ? true : false;
  }
  else {
    isSuccess = (semaphore_wait(semId) == KERN_SUCCESS) ? true : false;
  }
#else
  if (0 < timeoutSec) {
    timespec absTimeout;
    absTimeout.tv_sec = timeoutSec;
    absTimeout.tv_nsec = 0;
    isSuccess = (sem_timedwait(&semId, &absTimeout) == 0)  ? true : false;
  }
  else {
    isSuccess = (sem_wait(&semId) == 0)  ? true : false;
  }
#endif
  
  return isSuccess;
}
Beispiel #13
0
static cs_error_t
reply_receive_in_buf (
	struct ipc_instance *ipc_instance,
	void **res_msg)
{
#if _POSIX_THREAD_PROCESS_SHARED < 1
	struct sembuf sop;
#else
	struct timespec timeout;
	struct pollfd pfd;
#endif
	int res;

#if _POSIX_THREAD_PROCESS_SHARED > 0
retry_semwait:
	timeout.tv_sec = time(NULL) + IPC_SEMWAIT_TIMEOUT;
	timeout.tv_nsec = 0;

	res = sem_timedwait (&ipc_instance->control_buffer->sem1, &timeout);
	if (res == -1 && errno == ETIMEDOUT) {
		pfd.fd = ipc_instance->fd;
		pfd.events = 0;

		poll (&pfd, 1, 0);
		if (pfd.revents == POLLERR || pfd.revents == POLLHUP) {
			return (CS_ERR_LIBRARY);
		}

		goto retry_semwait;
	}

	if (res == -1 && errno == EINTR) {
		goto retry_semwait;
	}
#else
	/*
	 * Wait for semaphore #1 indicating a new message from server
	 * to client in the response queue
	 */
	sop.sem_num = 1;
	sop.sem_op = -1;
	sop.sem_flg = 0;

retry_semop:
	res = semop (ipc_instance->semid, &sop, 1);
	if (res == -1 && errno == EINTR) {
		return (CS_ERR_TRY_AGAIN);
	} else
	if (res == -1 && errno == EACCES) {
		priv_change_send (ipc_instance);
		goto retry_semop;
	} else
	if (res == -1) {
		return (CS_ERR_LIBRARY);
	}
#endif

	*res_msg = (char *)ipc_instance->response_buffer;
	return (CS_OK);
}
Beispiel #14
0
void *data_thread_function(void *arg) {
    /* This thread reads data out of a ring buffer through a callback */
    BufferSocket *bs = (BufferSocket *)arg;
    RING_ITEM *this_slot;
    struct timespec ts;

    while (bs->run_threads) {
        this_slot = bs->buf->read_ptr;
        if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
            fprintf(stderr, "Data: clock_gettime returned nonzero.\n");
            bs->run_threads = 0;
            continue;
        }
        ts.tv_nsec += 10000000;     // 10 ms
        // Wait for next buffer slot to fill up
        if (sem_timedwait(&this_slot->read_mutex, &ts) == -1) continue;
         //printf("Reading in a packet: size=%d slot=%d\n", this_slot->size, this_slot - bs->buf->list_ptr);
        // Feed data from buffer slot to callback function
        if (bs->callback((char *)this_slot->data, 
                this_slot->size, bs->userdata) != 0) {
            fprintf(stderr, "Data: Callback returned nonzero.\n");
            //bs->run_threads = 0;
        } else {
            // Release this slot for writing
            sem_post(&this_slot->write_mutex);
            bs->buf->read_ptr = this_slot->next;
        }
    }
    return NULL;
}
Beispiel #15
0
// Wait for a component to transition to the specified state
OMX_ERRORTYPE COpenMax::WaitForState(OMX_STATETYPE state)
{
  OMX_ERRORTYPE omx_error = OMX_ErrorNone;
  OMX_STATETYPE test_state;
  int tries = 0;
  struct timespec timeout;
  omx_error = OMX_GetState(m_omx_decoder, &test_state);

  #if defined(OMX_DEBUG_VERBOSE)
  CLog::Log(LOGDEBUG, "%s::%s - waiting for state(%d)\n", CLASSNAME, __func__, state);
  #endif
  while ((omx_error == OMX_ErrorNone) && (test_state != state)) 
  {
    clock_gettime(CLOCK_REALTIME, &timeout);
    timeout.tv_sec += 1;
    sem_timedwait(m_omx_decoder_state_change, &timeout);
    if (errno == ETIMEDOUT)
      tries++;
    if (tries > 5)
      return OMX_ErrorUndefined;

    omx_error = OMX_GetState(m_omx_decoder, &test_state);
  }

  return omx_error;
}
Beispiel #16
0
static int sleep_until_start_request_or_inactivity()
{
  SHOW_TIME("fifo > sleep_until_start_request_or_inactivity > ENTER");
  int a_start_is_required=0;

  // Wait for the start request (my_sem_start_is_required).
  // Besides this, if the audio stream is still busy, 
  // check from time to time its end. 
  // The end of the stream is confirmed by several checks 
  // for filtering underflow.
  //
  int i=0;
	while((i<= MAX_INACTIVITY_CHECK) && !a_start_is_required)
	{
		if (wave_is_busy( NULL) )
		{
			i = 0;
		}
      else
		{
			i++;
		}

		int err=0;
		struct timespec ts;
		struct timeval tv;

		clock_gettime2( &ts);

#ifdef DEBUG_ENABLED
		struct timespec to;
		to.tv_sec = ts.tv_sec;
		to.tv_nsec = ts.tv_nsec;
#endif

		add_time_in_ms( &ts, INACTIVITY_TIMEOUT);

		SHOW("fifo > sleep_until_start_request_or_inactivity > start sem_timedwait (start_is_required) from %d.%09lu to %d.%09lu \n", 
			to.tv_sec, to.tv_nsec,
			ts.tv_sec, ts.tv_nsec);

		while ((err = sem_timedwait(&my_sem_start_is_required, &ts)) == -1 
			&& errno == EINTR)
		{
			continue;
		}

		assert (gettimeofday(&tv, NULL) != -1);
		SHOW("fifo > sleep_until_start_request_or_inactivity > stop sem_timedwait (start_is_required, err=%d) %d.%09lu \n", err, 
			tv.tv_sec, tv.tv_usec*1000);

		if (err==0)
		{
			a_start_is_required = 1;
		}
	}
	SHOW_TIME("fifo > sleep_until_start_request_or_inactivity > LEAVE");
	return a_start_is_required;
}
bool Semaphore::wait(uint32_t timeout) {
	timespec tsAbsTimeout;
	clock_gettime(CLOCK_REALTIME, &tsAbsTimeout);
	uint64_t absTimeout = ((uint64_t)tsAbsTimeout.tv_nsec) + (uint64_t)(timeout * 1000000LL);
	tsAbsTimeout.tv_sec += absTimeout / 1000000000LL;
	tsAbsTimeout.tv_nsec = absTimeout % 1000000000LL;
	return (sem_timedwait(&mSemaphore, &tsAbsTimeout) == 0);
}
Beispiel #18
0
int main(int argc, char *argv[])
{
    int rc;
    sem_t sem;
    struct timespec tp;

    rc = sem_init(&sem, PTHREAD_PROCESS_PRIVATE, 1);
    assert(rc == 0);
    printf("sem_init passed\n");

/*
    rc = sem_wait(sem);
    assert(rc == 0);
    printf("sem_wait passed\n");
*/
    rc = sem_trywait(sem);
    assert(rc == 0);
    printf("sem_trywait passed\n");

    arch_time_in_timespec(&tp);

    tp.tv_sec += 1;
    tp.tv_nsec += 15625000;
    if (tp.tv_nsec >= POW10_9) {
        tp.tv_nsec -= POW10_9;
        tp.tv_sec += 1;
    }
    rc = sem_timedwait(sem, &tp);
    assert(rc == -1);
    assert(errno == ETIMEDOUT);
    printf("sem_timedwait passed\n");

    rc = sem_post(sem);
    assert(rc == 0);
    printf("sem_post passed\n");

    rc = sem_destroy(sem);
    assert(rc == 0);
    printf("sem_destroy passed\n");

    sem = sem_open("MySem", 0, 0, 1);
    assert(sem == NULL);
    printf("sem_open passed\n");

    sem = sem_open("MySem", O_CREAT, 0, 1);
    assert(sem != NULL);
    printf("sem_open with create passed\n");

    rc = sem_close(sem);
    assert(rc == 0);
    printf("sem_close passed\n");

    rc = sem_unlink("MySem");
    assert(rc == 0);
    printf("sem_unlink passed\n");

    return 0;
}
Beispiel #19
0
static int
do_test (void)
{
  sem_t s;
  if (sem_init (&s, 0, 0) == -1)
    {
      puts ("sem_init failed");
      return 1;
    }

  struct timeval tv;
  if (gettimeofday (&tv, NULL) != 0)
    {
      puts ("gettimeofday failed");
      return 1;
    }

  struct timespec ts;
  TIMEVAL_TO_TIMESPEC (&tv, &ts);

  /* Set ts to yesterday.  */
  ts.tv_sec -= 86400;

  int type_before;
  if (pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &type_before) != 0)
    {
      puts ("first pthread_setcanceltype failed");
      return 1;
    }

  errno = 0;
  if (TEMP_FAILURE_RETRY (sem_timedwait (&s, &ts)) != -1)
    {
      puts ("sem_timedwait succeeded");
      return 1;
    }
  if (errno != ETIMEDOUT)
    {
      printf ("sem_timedwait return errno = %d instead of ETIMEDOUT\n",
	      errno);
      return 1;
    }

  int type_after;
  if (pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, &type_after) != 0)
    {
      puts ("second pthread_setcanceltype failed");
      return 1;
    }
  if (type_after != PTHREAD_CANCEL_DEFERRED)
    {
      puts ("sem_timedwait changed cancellation type");
      return 1;
    }

  return 0;
}
Beispiel #20
0
int lxclock(struct lxc_lock *l, int timeout)
{
	int ret = -1, saved_errno = errno;
	struct flock lk;

	switch(l->type) {
	case LXC_LOCK_ANON_SEM:
		if (!timeout) {
			ret = sem_wait(l->u.sem);
			if (ret == -1)
				saved_errno = errno;
		} else {
			struct timespec ts;
			if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
				ret = -2;
				goto out;
			}
			ts.tv_sec += timeout;
			ret = sem_timedwait(l->u.sem, &ts);
			if (ret == -1)
				saved_errno = errno;
		}
		break;
	case LXC_LOCK_FLOCK:
		ret = -2;
		if (timeout) {
			ERROR("Error: timeout not supported with flock");
			ret = -2;
			goto out;
		}
		if (!l->u.f.fname) {
			ERROR("Error: filename not set for flock");
			ret = -2;
			goto out;
		}
		if (l->u.f.fd == -1) {
			l->u.f.fd = open(l->u.f.fname, O_RDWR|O_CREAT,
					S_IWUSR | S_IRUSR);
			if (l->u.f.fd == -1) {
				ERROR("Error opening %s", l->u.f.fname);
				goto out;
			}
		}
		lk.l_type = F_WRLCK;
		lk.l_whence = SEEK_SET;
		lk.l_start = 0;
		lk.l_len = 0;
		ret = fcntl(l->u.f.fd, F_SETLKW, &lk);
		if (ret == -1)
			saved_errno = errno;
		break;
	}

out:
	errno = saved_errno;
	return ret;
}
Beispiel #21
0
static int barrier_mutex_lock_to(struct tagged_barrier_entry *b, struct timespec *abs_timeout)
{
	int err;
	err = sem_timedwait(&b->mutex, abs_timeout);
	if(err && errno == EINVAL) {
		BLTS_LOGGED_PERROR("Sync: ERROR while locking barrier mutex");
	}
	return err?-errno:0;
}
Beispiel #22
0
void airport_takeoff_plane(airport *ap) {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += 5;

    /* If we use sem_wait() here, we can get a deadlock while gracefully shutting down the application.
    * Therefore, this blocks for a maximum of 5 seconds */
    if (sem_timedwait(&ap->full, &ts) == 0) {
        /* Acquire mutex lock to protect buffer */
        pthread_mutex_lock(&(ap->baylock));

        int bay_nr = get_random_alloc_bay_nr(ap);
        plane *p = bay_unpark_plane(ap->bays[bay_nr]);

        printf("After staying at bay %d for %.2f seconds, plane %s is taking off ...\n", bay_nr, bay_get_occupation_time(ap->bays[bay_nr]) / 1000.0f, plane_get_name(p));
        bay_destroy(ap->bays[bay_nr]);
        ap->bays[bay_nr] = NULL;
        pthread_mutex_unlock(&(ap->baylock));

        /* take-off time is 2 seconds */

        int rw;

        pthread_mutex_lock(&(ap->runwaylock));
        if (sem_timedwait(&ap->runways, &ts) != 0) {
            pthread_mutex_unlock(&(ap->runwaylock));
            return;
        }
        sem_getvalue(&ap->runways, &rw);
        pthread_mutex_unlock(&(ap->runwaylock));
        /* landing time is 2 seconds */
        msleep(2000);
        sem_post(&ap->runways);

        pthread_mutex_lock(&(ap->baylock));
        printf("Plane %s has finished taking off on runway %d.\n", plane_get_name(p), rw);
        plane_destroy(p);
        pthread_mutex_unlock(&(ap->baylock));
        sem_post(&ap->empty);
        if (airport_is_empty(ap)) {
            printf("The airport is empty\n");
        }
    }
}
Beispiel #23
0
static int audio_read_packet(AVFormatContext *context, AVPacket *pkt)
{
    JackData *self = context->priv_data;
    struct timespec timeout = {0, 0};
    int test;

    /* Activate the JACK client on first packet read. Activating the JACK client
     * means that process_callback() starts to get called at regular interval.
     * If we activate it in audio_read_header(), we're actually reading audio data
     * from the device before instructed to, and that may result in an overrun. */
    if (!self->activated) {
        if (!jack_activate(self->client)) {
            self->activated = 1;
            av_log(context, AV_LOG_INFO,
                   "JACK client registered and activated (rate=%dHz, buffer_size=%d frames)\n",
                   self->sample_rate, self->buffer_size);
        } else {
            av_log(context, AV_LOG_ERROR, "Unable to activate JACK client\n");
            return AVERROR(EIO);
        }
    }

    /* Wait for a packet comming back from process_callback(), if one isn't available yet */
    timeout.tv_sec = av_gettime() / 1000000 + 2;
    if (sem_timedwait(&self->packet_count, &timeout)) {
        if (errno == ETIMEDOUT) {
            av_log(context, AV_LOG_ERROR,
                   "Input error: timed out when waiting for JACK process callback output\n");
        } else {
            av_log(context, AV_LOG_ERROR, "Error while waiting for audio packet: %s\n",
                   strerror(errno));
        }
        if (!self->client)
            av_log(context, AV_LOG_ERROR, "Input error: JACK server is gone\n");

        return AVERROR(EIO);
    }

    if (self->pkt_xrun) {
        av_log(context, AV_LOG_WARNING, "Audio packet xrun\n");
        self->pkt_xrun = 0;
    }

    if (self->jack_xrun) {
        av_log(context, AV_LOG_WARNING, "JACK xrun\n");
        self->jack_xrun = 0;
    }

    /* Retrieve the packet filled with audio data by process_callback() */
    av_fifo_generic_read(self->filled_pkts, pkt, sizeof(*pkt), NULL);

    if ((test = supply_new_packets(self, context)))
        return test;

    return 0;
}
Beispiel #24
0
u32_t sys_arch_sem_wait(sys_sem_t * sem, u32_t timeout)
{
    lk_time_t start = current_time();

    status_t err = sem_timedwait(sem, timeout ? timeout : INFINITE_TIME);
    if (err == ERR_TIMED_OUT)
        return SYS_ARCH_TIMEOUT;

    return current_time() - start;
}
Beispiel #25
0
int Semaphore::lock( int interval )
{
  TRACE(this);
  if ( interval == 0 ) {
    return sem_wait( &m_semaphore );
  } else {
    timespec tspec = intIntervalTotimespec( interval );
    return sem_timedwait( &m_semaphore, &tspec );
  }
}
void* test_semaphoreone_write(void* p) {
	while(writecount) {
		if (!sem_timedwait(&test_semaphoreone_semaphore,&test_semaphoreone_tval)) {
			write(fd_out,(void*)&test_semaphoreone_val,4);
			writecount--;
		}
	}
	test_semaphoreone_halt=true;
	return NULL;
}
Beispiel #27
0
int
ui_ipc_semtimedwait(enum UI_IPC_SEM e_sp, time_t tmout)
{
  struct timespec ts;
  if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
    return -1;
  }
  ts.tv_sec += tmout;
  return ( sem_timedwait(sems[e_sp], &ts) );
}
Beispiel #28
0
static acquire_result
acquire_lock(sem_t *sem, double timeout)
{
    int err;
    struct timespec deadline;

    if (timeout > 0) {
        if (deadline_from_timeout(timeout, &deadline)) {
            PyErr_SetString(PyExc_OverflowError,
                            "timeout value is too large");
            return ACQUIRE_ERROR;
        }
    }

    /* First try non-blocking acquire without releasing the GIL. If this fails
     * and we have a timeout, release the GIL and block until we get the lock
     * or the timeout expires. */

    do {
        err = sem_trywait(sem);
    } while (err != 0 && errno == EINTR);

    if (err == 0)
        return ACQUIRE_OK;

    if (errno != EAGAIN) {
        set_error(errno, "sem_trywait");
        return ACQUIRE_ERROR;
    }

    if (timeout == 0)
        return ACQUIRE_FAIL;

    Py_BEGIN_ALLOW_THREADS;

    do {
        if (timeout > 0)
            err = sem_timedwait(sem, &deadline);
        else
            err = sem_wait(sem);
    } while (err != 0 && errno == EINTR);

    Py_END_ALLOW_THREADS;

    if (err != 0) {
        if (timeout > 0 && errno == ETIMEDOUT)
            return ACQUIRE_FAIL;

        /* Should never happen */
        set_error(errno, timeout > 0 ? "sem_timedwait" : "sem_wait");
        return ACQUIRE_ERROR;
    }

    return ACQUIRE_OK;
}
Beispiel #29
0
int main(void) {
	void *d;
	struct xbee *xbee;
	struct xbee_con *con;
	xbee_err ret;
	unsigned char txRet;
	struct timespec to;

	if (sem_init(&ndComplete, 0, 0) != 0) {
		printf("sem_init() returned an error: %d - %s\n", errno, strerror(errno));
		return -1;
	}
	
	if ((ret = xbee_setup(&xbee, "xbee1", "/dev/ttyUSB0", 57600)) != XBEE_ENONE) {
		printf("ret: %d (%s)\n", ret, xbee_errorToStr(ret));
		return ret;
	}

	if ((ret = xbee_conNew(xbee, &con, "Local AT", NULL)) != XBEE_ENONE) {
		xbee_log(xbee, -1, "xbee_conNew() returned: %d (%s)", ret, xbee_errorToStr(ret));
		return ret;
	}

	if ((ret = xbee_conCallbackSet(con, nodeCB, NULL)) != XBEE_ENONE) {
		xbee_log(xbee, -1, "xbee_conCallbackSet() returned: %d", ret);
		return ret;
	}

	if ((ret = xbee_conTx(con, &txRet, "ND")) != XBEE_ENONE && (ret != XBEE_ETX && ret != XBEE_ETIMEOUT)) {
		xbee_log(xbee, -1, "xbee_conTx() returned: %d-%d", ret, txRet);
		return ret;
	}

	printf("ND Sent!... waiting for completion\n");

	clock_gettime(CLOCK_REALTIME, &to);
	to.tv_sec  += 10;
	if (sem_timedwait(&ndComplete, &to) != 0) {
		if (errno == ETIMEDOUT) {
			printf("Timeout while waiting for ND command to complete...\n");
		} else {
			printf("Error calling sem_timedwait()... sleeping for 10 seconds instead\n");
			sleep(10);
		}
	}

	if ((ret = xbee_conEnd(con)) != XBEE_ENONE) {
		xbee_log(xbee, -1, "xbee_conEnd() returned: %d", ret);
		return ret;
	}

	xbee_shutdown(xbee);

	return 0;
}
Beispiel #30
0
static void test_sem_null(void)
{
  int rv;
  int val;
  struct timespec to;

  rtems_test_assert( NULL == SEM_FAILED );

  errno = 0;
  rv = sem_init( NULL, 0, 0 );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_wait( NULL );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_post( NULL );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_wait( NULL );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_trywait( NULL );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  to.tv_sec = 1;
  to.tv_nsec = 1;
  errno = 0;
  rv = sem_timedwait( NULL, &to );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_getvalue( NULL, &val );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_destroy( NULL );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );

  errno = 0;
  rv = sem_close( NULL );
  rtems_test_assert( rv == -1 );
  rtems_test_assert( errno == EINVAL );
}