int FileQueue<T>::doPop(T *&pointer, bool block) { if (block) { sem_wait(&(this->_semPop)); } else { if (sem_trywait(&(this->_semPop)) != 0) { return ERROR_QUEUE_IS_EMPTY; } } pthread_mutex_lock(&_mutexReadWrite); openFile(); lseek(_file, _head, SEEK_SET); this->create(pointer); read(_file, pointer, this->_dataSize); _head = lseek(_file, 0L, SEEK_CUR); lseek(_file, 0L, SEEK_SET); write(_file, &_head, sizeof(off_t)); pthread_mutex_unlock(&_mutexReadWrite); return 0; }
int CSemaphore::wait(u_int32_t msec) { int ret = 0; u_int32_t wait_time = 0; if(INFINITE == msec) { while(0 != (ret = sem_wait(&m_semaphore)) && EINTR == errno); } else { struct timespec delay_time; delay_time.tv_sec = 0; delay_time.tv_nsec = 1000000; // 1ms = 1000us // 1us = 1000ns while (true) { ret = sem_trywait(&m_semaphore); if (0 == ret) break; if (EAGAIN != errno) { ret = -1; break; } if (msec <= wait_time) { ret = -1; break; } nanosleep(&delay_time, NULL); wait_time++; } } return ret; }
int main(int argc, char *argv[]) { /* sigint function for signal */ if (SIG_ERR == signal(SIGINT, sig_int)) { fprintf(stderr, "signal error :%s\n", strerror(errno)); } /* sem_open */ sem = sem_open(SEM_FILE, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, 1); if (SEM_FAILED == sem) { fprintf(stderr, "sem_open error :%s\n", strerror(errno)); exit(EXIT_FAILURE); } /* sem_wait */ int ret; ret = sem_trywait(sem); if (-1 == ret && EAGAIN == errno) { fprintf(stdout, "same process runing\n"); exit(EXIT_SUCCESS); } else if (-1 == ret) { fprintf(stderr, "sem_trywait error :%s\n", strerror(errno)); } for ( ; ; ) { write(STDOUT_FILENO, ".", sizeof(".")); sleep(1); } /* sem_close */ if (-1 == sem_close(sem)) { fprintf(stderr, "sem_close error :%s\n", strerror(errno)); } /* sem_unlink */ if (-1 == sem_unlink(SEM_FILE)) { fprintf(stderr, "sem_unlink error :%s\n", strerror(errno)); } return 0; }
HX_RESULT HXPthreadMacSemaphore::_TryWait() { HX_RESULT retVal = HXR_OK; int nResult = 0; nResult = sem_trywait( m_semaphore ); if( nResult<0 && errno == EAGAIN ) { retVal = HXR_WOULD_BLOCK; } else if( nResult < 0 ) { #ifdef _DEBUG fprintf( stderr, "Can't wait on semaphore: %d %s\n", errno, strerror(errno) ); #endif retVal = HXR_FAIL; } return retVal; }
static PyObject * semlock_iszero(SemLockObject *self) { #ifdef HAVE_BROKEN_SEM_GETVALUE if (sem_trywait(self->handle) < 0) { if (errno == EAGAIN) Py_RETURN_TRUE; return _PyMp_SetError(NULL, MP_STANDARD_ERROR); } else { if (sem_post(self->handle) < 0) return _PyMp_SetError(NULL, MP_STANDARD_ERROR); Py_RETURN_FALSE; } #else int sval; if (SEM_GETVALUE(self->handle, &sval) < 0) return _PyMp_SetError(NULL, MP_STANDARD_ERROR); return PyBool_FromLong((long)sval == 0); #endif }
static void test1_second_thread(void) { puts("second: sem_trywait"); if (sem_trywait(&s) == 0) { puts("second: sem_trywait failed"); } puts("second: sem_trywait done with == 0"); puts("second: wait for post"); if (sem_wait(&s) != 1) { puts("second: sem_wait failed"); } puts("second: sem was posted"); puts("second: end"); }
void *S2ESynchronizedObjectInternal::tryAquire() { SyncHeader *hdr = (SyncHeader*)m_sharedBuffer; #ifdef CONFIG_DARWIN if (__sync_lock_test_and_set(&hdr->lock, 0) != 0) { return NULL; } #else int ret; do { ret = sem_trywait(&hdr->lock); if (ret < 0 && errno == EAGAIN) { return NULL; } }while(ret); #endif return ((uint8_t*)m_sharedBuffer + m_headerSize); }
void smf_wait() { sem_t *sp; pthread_mutex_lock(&mutex); if(sem_trywait(&sem) == 0) pthread_mutex_unlock(&mutex); else { sp = (sem_t *)malloc(sizeof(sem_t)); sem_init(sp, 0, 0); _queue_push(sp); pthread_mutex_unlock(&mutex); sem_wait(sp); sem_destroy(sp); free(sp); } }
int amp_semaphore_trywait_PROPOSED(amp_semaphore_t semaphore) { assert(NULL != semaphore); errno = 0; int retval = sem_trywait(&semaphore->semaphore); int return_code = AMP_SUCCESS; if(0 != retval) { switch (errno) { case EAGAIN: /* Semaphore was already locked */ return_code = AMP_BUSY; break; default: assert(0); /* Programming error */ return_code = AMP_ERROR; } } return return_code; }
bool MMFMutex::Lock( uint32 dwTimeout ) { if( m_owner == pthread_self() ) { m_recursive_count++; return true; } bool bUseTimeout = (dwTimeout != 0); while(true) { bool bGotSemaphore = false; if( m_key == 0 ) { bGotSemaphore = (sem_trywait(&m_semaphore) == 0); } else { struct sembuf operations[1]; operations[0].sem_num = 0; operations[0].sem_op = -1; operations[0].sem_flg = SEM_UNDO|IPC_NOWAIT; bGotSemaphore = (semop(m_id, operations, 1) >= 0); } if( bGotSemaphore ) { m_owner = pthread_self(); m_recursive_count = 1; return true; } sleep(1); if( bUseTimeout ) { if( dwTimeout > 1000 ) dwTimeout -= 1000; else dwTimeout = 0; if( dwTimeout == 0 ) return false; } } }
static int write_jack(out123_handle *ao, unsigned char *buf, int len) { jack_handle_t *handle = (jack_handle_t*)ao->userptr; size_t bytes_left; unsigned int strike = 0; bytes_left = len; while(bytes_left && handle->alive) { size_t piece; debug("writing to ringbuffer"); /* No help: piece1 = jack_ringbuffer_write_space(handle->rb); */ piece = jack_ringbuffer_write(handle->rb, (char*)buf, bytes_left); debug1("wrote %"SIZE_P" B", (size_p)piece); buf += piece; bytes_left -= piece; /* Allow nothing being written some times, but not too often. Don't know how often in a row that would be supposed to happen. */ if(!piece) { if(++strike > 100) { if(!AOQUIET) error("Cannot write to ringbuffer."); break; } /* Avoid busy waiting and semaphore accumulation: Wait once on the semaphore, then clear it. We count on it being posted by the process callback and we are going to push new data so that that one gets the chance. */ sem_wait(&handle->sem); do errno = 0; while(sem_trywait(&handle->sem) == 0 || errno == EINTR); } else strike = 0; } return len-bytes_left; }
int main(void) { char semname[NAME_MAX - 4]; sem_t *mysemp; int val; snprintf(semname, sizeof(semname), "/" FUNCTION "_" TEST "_%ld", (long)getpid()); mysemp = sem_open(semname, O_CREAT, 0777, 1); if (mysemp == SEM_FAILED || mysemp == NULL) { perror(ERROR_PREFIX "sem_open"); return PTS_UNRESOLVED; } /* Lock Semaphore */ if (sem_trywait(mysemp) == -1) { perror(ERROR_PREFIX "trywait"); return PTS_UNRESOLVED; } if (sem_getvalue(mysemp, &val) < 0) { perror(ERROR_PREFIX "sem_getvalue"); return PTS_UNRESOLVED; } /* printf("Current value is: %d\n", val); */ if (val <= 0) { puts("TEST PASSED"); sem_close(mysemp); sem_unlink(semname); return PTS_PASS; } else { puts("TEST FAILED"); return PTS_FAIL; } }
void printf_bad_list_cleint_persistent(void) { printf(" USER NUMBER\n"); sem_t *sem_client = sem_open(SHARED_MEMORY_SEM, 0, 0600, 1); int trys = 1, sem_reopen = 0; if (sem_client != SEM_FAILED) { while (trys) { if (sem_trywait(sem_client) == 0) { if (bad_list_clents_global && (bad_list_clents_global != MAP_FAILED)) { long index = 0; for (index = 0; index < bad_list_clents_global->numbers; index++) { printf(" %-16s %ld\n", bad_list_clents_global->items[index].username, index); } } trys = 0; } else { if (errno == EAGAIN) { trys++; if (trys == 100) { trys = 1; sem_close(sem_client); sem_client = sem_open(SHARED_MEMORY_SEM, 0, 0600, 1); sem_reopen++; if (sem_reopen == 4) break; } } else { trys = 0; } } } sem_post(sem_client); sem_close(sem_client); } return; }
/** * Wait for a semaphore to be posted, or timeout. * @param sem the semaphore * @param timeout the maximum time to wait, in milliseconds * @return completion code */ int Thread_wait_sem(sem_type sem, int timeout) { /* sem_timedwait is the obvious call to use, but seemed not to work on the Viper, * so I've used trywait in a loop instead. Ian Craggs 23/7/2010 */ int rc = -1; #if !defined(WIN32) && !defined(WIN64) #define USE_TRYWAIT #if defined(USE_TRYWAIT) int i = 0; int interval = 10000; /* 10000 microseconds: 10 milliseconds */ int count = (1000 * timeout) / interval; /* how many intervals in timeout period */ #else struct timespec ts; #endif #endif FUNC_ENTRY; #if defined(WIN32) || defined(WIN64) rc = WaitForSingleObject(sem, timeout); #elif defined(USE_TRYWAIT) while (++i < count && (rc = sem_trywait(sem)) != 0) { if (rc == -1 && ((rc = errno) != EAGAIN)) { rc = 0; break; } usleep(interval); /* microseconds - .1 of a second */ } #else if (clock_gettime(CLOCK_REALTIME, &ts) != -1) { ts.tv_sec += timeout; rc = sem_timedwait(sem, &ts); } #endif FUNC_EXIT_RC(rc); return rc; }
void EventCtrl::runOnce_() { #ifndef MONO_THREAD sem_trywait(&queueSem); #endif if (eventQueue.size() == 0) return; #ifndef MONO_THREAD pthread_mutex_lock(&queueMutex); #endif while (eventQueue.size() > 0) { Event event = eventQueue.front(); eventQueue.pop(); #ifndef MONO_THREAD pthread_mutex_unlock(&queueMutex); #endif send(event); } }
BaseGDL* sem_lock(EnvT *e) { SizeT nParam = e->NParam(1); DString name; e->AssureStringScalarPar(0, name); sem_data_t &data = sem_get_data(name, e); if (sem_is_locked(data)) { // lock already held return new DIntGDL(1); } if (sem_trywait(data.sem) == 0) { sem_set_locked(data, true); return new DIntGDL(1); } return new DIntGDL(0); }
ClRcT cosPosixSemTryLock (ClOsalSemIdT semId) { ClInt32T retCode = CL_OK; sem_t *pSem = *(sem_t**)&semId; CL_FUNC_ENTER(); retCode = sem_trywait(pSem); if (-1 == retCode) { int err = errno; if (err == EAGAIN) return(CL_OSAL_RC(CL_OSAL_ERR_SEM_LOCK)); /* Taking the lock failed because the lock is taken by someone else */ else sysRetErrChkRet(err); /* Some unexpected error occurred */ } CL_FUNC_EXIT(); return (CL_OK); /* It worked, lock was taken */ }
int executeWithLock(char *name, LockFunc func) { int result = -1; int lock = -1; struct sigaction action; mutex = sem_open(name, O_CREAT | O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO, 1); if (mutex == SEM_FAILED) { //create failed. Probably lock is already created so try opening the existing lock. mutex = sem_open(name, 0); } if (mutex == SEM_FAILED) return -1; //this is an error. // install signal handler to free the lock if something bad happens. // sem_t is not freed automatically when a process ends. action.sa_handler = catch_signal; sigaction(SIGINT, &action, &intAction); sigaction(SIGQUIT, &action, &quitAction); while ((lock = sem_trywait(mutex)) != 0) { if (errno == EAGAIN) { //couldn't acquire lock, sleep a bit and try again sleep(1); if (--openFileTimeout > 0) continue; } break; } if (lock == 0) result = func(); sem_post(mutex); sem_close(mutex); //reinstall the original signal handlers sigaction(SIGINT, &intAction, NULL); sigaction(SIGQUIT, &quitAction, NULL); return result; }
int CSemaphore::Wait (int nTimeout) { #ifdef WIN32 if(nTimeout != INFINITE) { nTimeout*=1000; } int val = WaitForSingleObject(__m_hSem,nTimeout); if(val == WAIT_OBJECT_0) { return 0; } else { return val; } #else if(nTimeout == INFINITE) { return sem_wait(__m_hSem); } else { for(int i=0;i<nTimeout;i++) { if(sem_trywait(__m_hSem)==0) { return 0; } sleep(1); } return -1; } #endif }
int _LinkC_Recv(LinkC_Socket *Socket, void *Message, size_t size, int Flag){ if(List != NULL){ // 如果链表为空 LinkC_Debug("_LinkC_Recv: LinkC Socket Environment Not Initialized",LINKC_FAILURE); return LINKC_FAILURE; // 返回错误 } int Result=0; if(Flag == MSG_DONTWAIT) Result = sem_trywait(Socket->RecvList->Semaphore); // 非阻塞请求数据 else{ Result = sem_wait(Socket->RecvList->Semaphore); // 阻塞请求数据 } if(Result < 0){ perror("Sem Wait[Trywait]"); return 0; } pthread_mutex_lock(Socket->RecvList->MutexLock); // 上互斥锁 if(Socket->RecvList->TotalNode <= 0){ printf("Error Occurred [file = %s\tline = %d]\n",__FILE__,__LINE__); pthread_mutex_unlock(Socket->RecvList->MutexLock); // 解锁 return -1; } PackageListNode *Node = Socket->RecvList->StartNode; while(Node->Next) Node = Node->Next; // 跳转到最后一个Node if((Node->MessageLength)+(uint32_t)8 > size){ LinkC_Debug("_LinkC_Recv: Receive Buffer Too Small",LINKC_FAILURE); sem_post(Socket->RecvList->Semaphore); pthread_mutex_unlock(Socket->RecvList->MutexLock); return -1; } memcpy(Message,Node->Package,Node->MessageLength+8); if(Flag == MSG_PEEK){ pthread_mutex_unlock(Socket->RecvList->MutexLock); sem_post(Socket->RecvList->Semaphore); }else{ RemovePackageListNode(Socket->RecvList,((PackageHeader*)Message)->MessageCounts); pthread_mutex_unlock(Socket->RecvList->MutexLock); } return ((PackageHeader*)Message)->MessageLength; }
size_t ManualExecutor::run() { size_t count; size_t n; Action action; { std::lock_guard<std::mutex> lock(lock_); while (!scheduledActions_.empty()) { auto& sa = scheduledActions_.top(); if (sa.time > now_) break; actions_.push(sa.action); scheduledActions_.pop(); } n = actions_.size(); } for (count = 0; count < n; count++) { { std::lock_guard<std::mutex> lock(lock_); if (actions_.empty()) { break; } // Balance the semaphore so it doesn't grow without bound // if nobody is calling wait(). // This may fail (with EAGAIN), that's fine. sem_trywait(&sem_); action = std::move(actions_.front()); actions_.pop(); } action(); } return count; }
/******************************************************************************************************** 功能:信号量等待。 原型:int ipanel_porting_sem_wait(unsigned int handle, int wait_time) 参数说明: 输入参数: handle:信号量句柄,由ipanel_porting_sem_create获得。 wait_time:等待时间,单位为毫秒。为IPANEL_NO_WAIT(0)时表示不等待立即返回,为IPANEL_WAIT_FOREVER(-1)表示永久等待 输出参数:无 返 回: IPANEL_OK:成功, IPANEL_ERR:失败 ********************************************************************************************************/ int ipanel_porting_sem_wait(unsigned int handle, int wait_time) { OsSem *pSem = (OsSem*)handle; if (pSem==NULL) { return IPANEL_ERR; } if (0==wait_time) { if (sem_trywait(&pSem->sem) == 0) return IPANEL_OK; } else if (-1==wait_time) { if (sem_wait(&pSem->sem) == 0) return IPANEL_OK; } else if (wait_time>0) { struct timeval temptime; gettimeofday(&temptime, NULL); temptime.tv_sec += (wait_time/1000); temptime.tv_usec += (wait_time%1000)*1000; if (sem_timedwait(&pSem->sem, &temptime) == 0) return IPANEL_OK; } if (errno != ETIMEDOUT) { if (errno == EDEADLK) { ; } } return IPANEL_ERR; }
// Producer code void *producer(void *argument) { int *prodNo = (int *) argument; // Producers identifying number Node *node; // Produced node while(1) { // Produce or stop int tw = sem_trywait(&products_remaining); if(tw == -1) // If there are no more products to be produced, end thread. { pthread_exit(0); } else if(tw == 0) // There are more products be produced. { node = produceProduct(); // Final product } else { printf("Some error occured when trying to wait on products_remaining semaphore"); } // Add product to buffer sem_wait(&empty); // Wait for room in buffer. list_add(itemList, node); // Add node to list. // Increase count of number products in buffer. pthread_mutex_lock(&products_buffer_lock); products_in_buffer++; printf("Producer %d produced %s. Items in buffer: %d (out of %d) \n", *prodNo, node->elm, products_in_buffer, buffer_size); pthread_mutex_unlock(&products_buffer_lock); sem_post(&full); // Signal full so buffer space is decreased by 1. // Sleep for random time. sleepRandom(10000); } }
int main() { sem_t *mysemp; char semname[20]; int val; sprintf(semname, "/" FUNCTION "_" TEST "_%d", getpid()); /* Initial value of Semaphore is 1 */ mysemp = sem_open(semname, O_CREAT, 0777, 1); if( mysemp == SEM_FAILED || mysemp == NULL ) { perror(ERROR_PREFIX "sem_open"); return PTS_UNRESOLVED; } /* Lock Semaphore by sem_trywait*/ if( sem_trywait(mysemp) == -1 ) { perror(ERROR_PREFIX "sem_wait"); return PTS_UNRESOLVED; } /* Value of Semaphore */ if( sem_getvalue(mysemp, &val) == -1 ) { perror(ERROR_PREFIX "sem_getvalue"); return PTS_UNRESOLVED; /* Checking if the value of the Semaphore decremented by one */ } else if( val == 0 ) { puts("TEST PASSED"); sem_unlink(semname); sem_close(mysemp); return PTS_PASS; } else { puts("TEST FAILED"); return PTS_FAIL; } }
void *mqueue_tryget(mqueue_t *queue) { int s = sem_trywait(&queue->sema); pthread_mutex_lock(&queue->lock); if(s < 0 || queue->first == NULL) { pthread_mutex_unlock(&queue->lock); return NULL; } void *tmp = *queue->first; *queue->first = NULL; queue->first++; queue->count--; if(queue->first == queue->elements + queue->size) queue->first = queue->elements; pthread_mutex_unlock(&queue->lock); return tmp; }
int dma_free(dma_chain_t * chain) { int irq = 0; if (chain == NULL) return -1; if (!irq_inside_int()) irq = irq_disable(); /* mark we won't wait on the semaphore */ chain->src = NULL; if (!chain->dest) { /* the semaphore has been signaled already */ assert(!sem_trywait(chain->sema)); free_chain(chain); } if (!irq_inside_int()) irq_restore(irq); return 0; }
/* * pj_sem_trywait() */ PJ_DEF(pj_status_t) pj_sem_trywait(pj_sem_t *sem) { #if PJ_HAS_THREADS int result; PJ_CHECK_STACK(); PJ_ASSERT_RETURN(sem, PJ_EINVAL); result = sem_trywait( sem->sem ); if (result == 0) { PJ_LOG(6, (sem->obj_name, "Semaphore acquired by thread %s", pj_thread_this()->obj_name)); } if (result == 0) return PJ_SUCCESS; else return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #else pj_assert( sem == (pj_sem_t*)1 ); return PJ_SUCCESS; #endif }
bool Semaphore::tryWait() { #if defined WIN32 return ::WaitForSingleObject (_semaphore, 0) == WAIT_OBJECT_0; #elif HAVE_PTHREAD && HAVE_POSIX_SEMAPHORES return sem_trywait (&_semaphore) == 0; #elif HAVE_PTHREAD && !HAVE_POSIX_SEMAPHORES ::pthread_mutex_lock (&_semaphore.mutex); if (_semaphore.count == 0) { ::pthread_mutex_unlock (&_semaphore.mutex); return false; } else { _semaphore.count--; ::pthread_mutex_unlock (&_semaphore.mutex); return true; } #endif }
u32_t sys_arch_mbox_tryfetch(sys_mbox_t * mbox, void **msg) { //LTRACE_ENTRY; status_t res; res = sem_trywait(&mbox->full); if (res == ERR_NOT_READY) { //LTRACE_EXIT; return SYS_MBOX_EMPTY; } mutex_acquire(&mbox->lock); *msg = mbox->queue[mbox->tail]; mbox->tail = (mbox->tail + 1) % mbox->size; mutex_release(&mbox->lock); sem_post(&mbox->empty, true); //LTRACE_EXIT; return 0; }
/* buildQueue: reads lines from the input file, where each * line contains a different client. * TODO: work with a limited shared queue size for extra credit */ int buildQueue(char * filename) { int num_clients = 0; FILE *fp; char line[FILENAME_SIZE]; //Get the file name fp = fopen(filename, "r");// read mode only if(fp == NULL) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } //read a line while(fgets(line, FILENAME_SIZE, fp) != NULL) { strtok(line, "\n"); // get rid of newline if(sem_trywait(&full)) { printf("Waiting to add clients to the full queue\n"); sem_wait(&full); } sem_wait(&queue_access); enqueue(line); sem_post(&queue_access); sem_post(&empty); num_clients += 1; } fclose(fp); return num_clients; }