static void thread_close( UBuffer* port ) { ThreadExt* ext = (ThreadExt*) port->ptr.v; ThreadQueue* queue; uint8_t endOpen; queue = (port->SIDE == SIDE_A) ? &ext->A : &ext->B; mutexLock( queue->mutex ); endOpen = queue->END_OPEN; mutexUnlock( queue->mutex ); if( endOpen ) { queue = (port->SIDE == SIDE_A) ? &ext->B : &ext->A; mutexLock( queue->mutex ); queue->END_OPEN = 0; mutexUnlock( queue->mutex ); } else { _freeThreadQueue( &ext->A ); _freeThreadQueue( &ext->B ); memFree( port->ptr.v ); //printf( "KR thread_close\n" ); } //pbuf->ptr.v = 0; // Done by port_destroy(). }
int lwip_sock_read(void *conn, unsigned char *buff, unsigned long len) { struct netbuf *new_buf=0; unsigned char *data; int data_len=0; int ret,newret; SYSCALL_DEBUG(" SOCK read :%x len:%d \n",buff,len); mutexLock(g_netBH_lock); ret=netconn_recv(conn, &new_buf); mutexUnLock(g_netBH_lock); if (ret!=ERR_OK){ SYSCALL_DEBUG(" Fail to recv data: %x newret:%x(%d) \n",ret,-ret,-ret); return 0; } netbuf_data(new_buf,&data,&data_len); SYSCALL_DEBUG(" SUCESS to recv data:%d ret:%d\n",data_len,ret); if (data_len > 0){ ut_memcpy(buff,data,ut_min(data_len,len)); ret = ut_min(data_len,len); }else{ ret = 0; } mutexLock(g_netBH_lock); netbuf_delete(new_buf); mutexUnLock(g_netBH_lock); return ret; }
void ArrayCache::ComputeState::produce( size_t index, void *data ) const { { Util::Mutex::Lock mutexLock( m_mutex ); if ( m_arrayCache->m_cacheDataExists.size() > index && m_arrayCache->m_cacheDataExists[ index ] ) { m_arrayCache->m_inputElementDesc->setData( &m_arrayCache->m_cacheData[ index * m_arrayCache->m_inputElementDesc->getAllocSize() ], data ); return; } } m_inputArrayProducerComputeState->produce( index, data ); { Util::Mutex::Lock mutexLock( m_mutex ); size_t arraySize = getCount(); size_t allocSize = m_arrayCache->m_inputElementDesc->getAllocSize(); if ( m_arrayCache->m_cacheDataExists.size() < arraySize ) { m_arrayCache->m_cacheData.resize( allocSize * arraySize, 0 ); m_arrayCache->m_cacheDataExists.resize( arraySize, 0 ); } if ( index < arraySize ) { m_arrayCache->m_inputElementDesc->setData( data, &m_arrayCache->m_cacheData[ index * allocSize ] ); m_arrayCache->m_cacheDataExists[ index ] = true; } } }
ArrayCache::ComputeState::ComputeState( RC::ConstHandle<ArrayCache> const &arrayCache ) : ArrayProducer::ComputeState( arrayCache ) , m_arrayCache( arrayCache ) , m_inputArrayProducerComputeState( arrayCache->m_inputArrayProducer->createComputeState() ) , m_mutex( arrayCache->m_mutex ) { // andrewmacp 2012-01-19: // It wouldn't be incorrect to do this without a mutex but it's // clearer and simpler to leave one in, we may remove later. { Util::Mutex::Lock mutexLock( m_arrayCache->m_mutex ); if ( m_arrayCache->m_cacheCountExists ) { setCount( m_arrayCache->m_cacheCount ); return; } } size_t count = m_inputArrayProducerComputeState->getCount(); setCount( count ); { Util::Mutex::Lock mutexLock( m_arrayCache->m_mutex ); m_arrayCache->m_cacheCount = count; m_arrayCache->m_cacheCountExists = true; } }
void exitSection(int id) { // LEAVE THESE STATEMENTS int isFemale = femaleOnly ? 1 : (id % 2 == 0); // TODO: Complete this function if (isFemale) { mutexLock(id, &femaleCountMutex); //pthread_mutex_lock(&femaleCountMutex); femaleCount--; if (femaleCount == 0) { // sem_post(&male); semPost(id, &male); } mutexUnlock(id, &femaleCountMutex); //pthread_mutex_unlock(&femaleCountMutex); } else { mutexLock(id, &maleCountMutex); //pthread_mutex_lock(&maleCountMutex); maleCount--; if (maleCount == 0) { // sem_post(&female); semPost(id, &female); } mutexUnlock(id, &maleCountMutex); //pthread_mutex_unlock(&maleCountMutex); } }
void queueClear(QueueClass *queue) { mutexLock(&queue->readMutex); mutexLock(&queue->writeMutex); queue->dataBegin = 0; queue->dataEnd = 0; mutexUnlock(&queue->writeMutex); mutexUnlock(&queue->readMutex); eventSourceSendSignal(&queue->readEventSource); }
static void netfront_input(struct netif *netif, unsigned char* data, int len) { struct eth_hdr *ethhdr; struct pbuf *p, *q; int ret; #if ETH_PAD_SIZE len += ETH_PAD_SIZE; /* allow room for Ethernet padding */ #endif /* move received packet into a new pbuf */ mutexLock(g_netBH_lock); p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL); mutexUnLock(g_netBH_lock); if (p == NULL) { LINK_STATS_INC(link.memerr); LINK_STATS_INC(link.drop); error_mem++; return; } #if ETH_PAD_SIZE pbuf_header(p, -ETH_PAD_SIZE); /* drop the padding word */ #endif /* We iterate over the pbuf chain until we have read the entire * packet into the pbuf. */ for (q = p; q != NULL && len > 0; q = q->next) { /* Read enough bytes to fill this pbuf in the chain. The * available data in the pbuf is given by the q->len * variable. */ ut_memcpy(q->payload, data, len < q->len ? len : q->len); data += q->len; len -= q->len; } #if ETH_PAD_SIZE pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */ #endif LINK_STATS_INC(link.recv); /* points to packet payload, which starts with an Ethernet header */ ethhdr = p->payload; mutexLock(g_netBH_lock); if (ethernet_input(p, netif) != ERR_OK){ BUG(); pbuf_free(p); } mutexUnLock(g_netBH_lock); }
void queueResize(QueueClass *queue, int newSize) { mutexLock(&queue->readMutex); mutexLock(&queue->writeMutex); if (queue->buffer) { free(queue->buffer); } queue->elementMaxCount = newSize; queue->buffer = malloc(queue->elementSize * queue->elementMaxCount); queue->dataBegin = 0; queue->dataEnd = 0; mutexUnlock(&queue->writeMutex); mutexUnlock(&queue->readMutex); eventSourceSendSignal(&queue->readEventSource); }
/** * Creates a combination of robot and AprilTag data */ int fetchData(char *buffer, int rid, int rhead, int aid, int ahead) { int n = 2; char *bufp; if (rid != -1) { mutexLock(&robots[rid].mutex); if (rhead == -1) { rhead = ((robots[rid].head - 1) % NUMBUFFER + NUMBUFFER) % NUMBUFFER; } n = sprintf(buffer, "%s", robots[rid].buffer[rhead]); mutexUnlock(&robots[rid].mutex); if (n < 0) { return (-1); } } if (aid != -1) { bufp = buffer + n - 2; mutexLock(&aprilTagData[aid].mutex); if (ahead == -1) { ahead = ((aprilTagData[aid].head - 1) % NUMBUFFER_APRILTAG + NUMBUFFER_APRILTAG) % NUMBUFFER_APRILTAG; } if (rid != -1) { n = sprintf(bufp, ", %s", aprilTagData[aid].buffer[ahead]); } else { n = sprintf(bufp, "%s", aprilTagData[aid].buffer[ahead]); } mutexUnlock(&aprilTagData[aid].mutex); if (n < 0) { return (-1); /* If there was no data, rewrite the CRLF */ } else if (n == 2) { if (sprintf(bufp, "\r\n") < 0) { return (-1); } } } return (0); }
void strfree(const char *s) { sp_item_t *item,*key; if (!s) return; if (!stringpool) return; mutexLock(&sp_mutex); key = (sp_item_t *)(s - offsetof(sp_item_t, str)); if ((item = (sp_item_t *)arrayFind(stringpool, key)) != NULL && item == key) { item->ref_count --; if (!item->ref_count) { arrayRemove(stringpool, item); free(item); } } mutexUnlock(&sp_mutex); }
/** * Get complete node IDs and type for log messages from numerical ID. * * Note: This method is expensive, so use this function only in performance uncritical code paths. * If you already have a Node object, call node->getNodeIDWithTypeStr() directly. */ std::string NodeStoreServers::getNodeIDWithTypeStr(uint16_t numID) { SafeMutexLock mutexLock(&mutex); // L O C K std::string nodeID; NodeMapIter iter = activeNodes.find(numID); if(iter != activeNodes.end() ) { // node exists in active store NodeReferencer* nodeRefer = iter->second; Node* node = nodeRefer->getReferencedObject(); nodeID = node->getNodeIDWithTypeStr(); } else if(localNode && (numID == localNode->getNumID() ) ) nodeID = localNode->getNodeIDWithTypeStr(); else nodeID = std::string("Unknown node: ") + Node::nodeTypeToStr(storeType) + " [ID: " + StringTk::uintToStr(numID) + "]"; mutexLock.unlock(); // U N L O C K return nodeID; }
void Synchronizer::wakeupAll() { mutexLock(&mMutex); mShared = 1; conditionVarBroadcast(&mCondition); mutexUnlock(&mMutex); }
/** * This is used to iterate over all stored nodes. * Start with this and then use referenceNextNode() until it returns NULL. * * Note: remember to call releaseNode() * * @return can be NULL if localNode is not included */ Node* NodeStoreServers::referenceFirstNode() { SafeMutexLock mutexLock(&mutex); // L O C K Node* resultNode = NULL; NodeReferencer localNodeRefer(localNode, false); /* don't move this into if-brackets, because it would be removed from stack then and we need to access it again further below.*/ if(localNode) // insert local node activeNodes.insert(NodeMapVal(localNode->getNumID(), &localNodeRefer) ); NodeMapIter iter = activeNodes.begin(); if(iter != activeNodes.end() ) { NodeReferencer* nodeRefer = iter->second; resultNode = nodeRefer->reference(); } if(localNode) // remove local node activeNodes.erase(localNode->getNumID() ); mutexLock.unlock(); // U N L O C K return resultNode; }
extern float stopTimer() { Thread thread; threadCurrent(&thread); mutexLock(&(timerStack.mutex)); int i = timerStack.top - 1; while (i >= 0) { if (timerStack.stack[i].thread == thread) { break; } i--; } double start = timerStack.stack[i].time; while (i < timerStack.top - 1) { timerStack.stack[i] = timerStack.stack[i + 1]; i++; } timerStack.top--; mutexUnlock(&(timerStack.mutex)); double end = getTime(); return (float) (end - start); }
epicsShareFunc void epicsShareAPI epicsThreadShow(epicsThreadId showThread, unsigned int level) { epicsThreadOSD *pthreadInfo; int status; int found = 0; epicsThreadInit(); if(!showThread) { showThreadInfo(0,level); return; } status = mutexLock(&listLock); checkStatusQuit(status,"pthread_mutex_lock","epicsThreadShowAll"); pthreadInfo=(epicsThreadOSD *)ellFirst(&pthreadList); while(pthreadInfo) { if (((epicsThreadId)pthreadInfo == showThread) || ((epicsThreadId)pthreadInfo->tid == showThread)) { found = 1; showThreadInfo(pthreadInfo,level); } pthreadInfo=(epicsThreadOSD *)ellNext(&pthreadInfo->node); } status = pthread_mutex_unlock(&listLock); checkStatusQuit(status,"pthread_mutex_unlock","epicsThreadShowAll"); if (!found) printf("Thread %#lx (%lu) not found.\n", (unsigned long)showThread, (unsigned long)showThread); }
QTSS_Error RedisJudgeStreamID(QTSS_JudgeStreamID_Params* inParams) { //算法描述,删除指定sessionID对应的key,如果成功删除,表明SessionID存在,验证通过,否则验证失败 OSMutexLocker mutexLock(&sMutex); if (!sIfConSucess) return QTSS_NotConnected; bool bReval = false; char chKey[128] = { 0 }; sprintf(chKey, "SessionID_%s", inParams->inStreanID);//如果key存在则返回整数类型1,否则返回整数类型0 int ret = sRedisClient->Delete(chKey); if (ret == -1)//fatal err,need reconnect { sRedisClient->Free(); sIfConSucess = false; return QTSS_NotConnected; } else if (ret == 0) { *(inParams->outresult) == 1; return QTSS_NoErr; } else { return ret; } }
bool CGitStatus::GetRepoRootInternal(const wstring& path, wstring& repoRoot_out, git_buf &buf, git_repository *&repo) { // This is temporary. CMutexLock mutexLock(&m_mutex); SecureZeroMemory(&buf, sizeof(git_buf)); wstring_convert<codecvt_utf8<wchar_t>> converter; string cpath = converter.to_bytes(path); if (git_repository_discover(&buf, cpath.c_str(), 0, NULL)) { Logger::LogWarning(_T("Unable to find git repository")); return false; } if (git_repository_open(&repo, buf.ptr)) { Logger::LogError(_T("Unable to open repository")); git_buf_free(&buf); return false; } const char* workDir = git_repository_workdir(repo); if (workDir == nullptr) { Logger::LogWarning(_T("No working directory. Probably bare repository.")); git_buf_free(&buf); return false; } repoRoot_out = MyUtils::NormalizePath(converter.from_bytes(workDir)); return true; }
HIDDEN void IOIntHandler(unsigned int devAddr, unsigned int devCommand) { unsigned int cpuID = getPRID(); memaddr *devCommandReg; // Esegue una V sul semaforo del device, risvegliando il primo processo bloccato unsigned char unlockedProcess = devSemV(devAddr); if(unlockedProcess == FALSE) saveRetDevStatus(devAddr); mutexLock(getDevDbMutex()); /* Mando l'ack dell'interrupt */ devCommandReg = (memaddr *) devCommand; *devCommandReg = DEV_C_ACK; mutexUnlock(getDevDbMutex()); if(getCurrentProcess(cpuID) != NULL) // RILANCIO IL PROCESSO CHE ESEGUIVA SULLA CPU currentProcessRestart(cpuID, FALSE); else { processInterleave(NULL); currentProcessRestart(cpuID, TRUE); } }
/** * Set internal root node ID. * * @return false if the new ID was rejected (e.g. because we already had an id set and * ignoreExistingRoot was false). */ bool NodeStoreServers::setRootNodeNumID(uint16_t id, bool ignoreExistingRoot) { // don't allow invalid id 0 (if not forced to do so) if(!id && !ignoreExistingRoot) return false; SafeMutexLock mutexLock(&mutex); // L O C K bool setRootRes = true; if(!this->rootNodeID) { // no root defined yet => set the new root this->rootNodeID = id; } else if(!ignoreExistingRoot) { // root defined already, reject new root setRootRes = false; } else { // root defined already, but shall be ignored this->rootNodeID = id; } mutexLock.unlock(); // U N L O C K return setRootRes; }
int np_continue(sys_thread_t *tid) { int count, ret = 0; int err = mutexLock(&sr_lock); sysAssert(err == 0); count = --tid->suspend_count; #ifdef LOG_THREADS dprintf(2, "[Resuming fromtid = %ld, tid = %ld, pid = %d, count = %d]\n", pthread_self(), tid->sys_thread, tid->lwp_id, count); #endif if (count == 0) { if (tid->selfsuspended) { tid->selfsuspended = 0; sem_post(&tid->sem_selfsuspend); } else { sr_tid = tid; ret = pthread_kill(tid->sys_thread, sr_sigresu); } #ifdef LOG_THREADS dprintf(2, "[Resumed fromtid = %ld, pthread_kill(%ld, %d) = %d]\n", pthread_self(), tid->sys_thread, sr_sigresu, ret); #endif } else if (count < 0) { /* Ignore attempts to resume a thread that has not been suspended */ tid->suspend_count = 0; } err = mutexUnlock(&sr_lock); sysAssert(err == 0); return ret == 0 ? SYS_OK : SYS_ERR; }
bool cMysqlDatabase::Open() { cMutexLock mutexLock(&mutex); mysql = mysql_init(NULL); if (!mysql) return false; mysql_library_init(0, NULL, NULL); mysql_options (mysql, MYSQL_OPT_CONNECT_TIMEOUT, "5"); std::string databaseName; std::string::size_type idx = path.find_last_of('/'); if (idx != std::string::npos) databaseName = path.substr(idx+1); else databaseName = path; // create the database if (!noCreate && !CreateDatabase(databaseName)) return false; MYSQL *m = mysql_real_connect (mysql, "127.0.0.1", "reeluser", "reeluser", databaseName.c_str(), 0, NULL, 0); if (!m) return false; return true; }
int mmapLogReadLine(char *buffer, uint16_t len) { MMAP_FILE_HEADER *hd; char *mdata; unsigned long rpos; int rlen; mutexLock(g_mmap_log.mutex, -1); hd = (MMAP_FILE_HEADER*)g_mmap_log.handle->data; mdata = (char*)g_mmap_log.handle->data; rpos = g_mmap_log.readpos; if(rpos == hd->writepos) rlen = -2; else { if(hd->endpos > hd->writepos && rpos >= hd->endpos) rpos = g_mmap_log.readpos = sizeof(MMAP_FILE_HEADER); rlen = *((uint16_t*)(mdata + rpos)); } if(rlen > 0 && len > rlen) { memcpy_s(buffer, len, mdata + rpos + sizeof(uint16_t), rlen); rpos += (rlen + sizeof(uint16_t)); g_mmap_log.readpos = rpos; } else if(rlen > 0) rlen = -1; mutexUnLock(g_mmap_log.mutex); return rlen; }
/** * Note: Holds lock while generating stats strings => slow => use carefully */ void MultiWorkQueue::getStatsAsStr(std::string& outIndirectQueueStats, std::string& outDirectQueueStats, std::string& outMirrorQueueStats, std::string& outBusyStats) { SafeMutexLock mutexLock(&mutex); // L O C K // get queue stats indirectWorkList->getStatsAsStr(outIndirectQueueStats); directWorkList->getStatsAsStr(outDirectQueueStats); mirrorWorkList->getStatsAsStr(outMirrorQueueStats); // number of busy workers std::ostringstream busyStream; busyStream << "* Busy workers: " << StringTk::uintToStr(stats.rawVals.busyWorkers) << std::endl; busyStream << "* Work Requests: " << StringTk::uintToStr(stats.incVals.workRequests) << " " "(reset every second)" << std::endl; busyStream << "* Bytes read: " << StringTk::uintToStr(stats.incVals.diskReadBytes) << " " "(reset every second)" << std::endl; busyStream << "* Bytes written: " << StringTk::uintToStr(stats.incVals.diskWriteBytes) << " " "(reset every second)" << std::endl; outBusyStats = busyStream.str(); mutexLock.unlock(); // U N L O C K }
static void * start_routine(void *arg) { epicsThreadOSD *pthreadInfo = (epicsThreadOSD *)arg; int status; int oldtype; sigset_t blockAllSig; sigfillset(&blockAllSig); pthread_sigmask(SIG_SETMASK,&blockAllSig,NULL); status = pthread_setspecific(getpthreadInfo,arg); checkStatusQuit(status,"pthread_setspecific","start_routine"); status = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&oldtype); checkStatusQuit(status,"pthread_setcanceltype","start_routine"); status = mutexLock(&listLock); checkStatusQuit(status,"pthread_mutex_lock","start_routine"); ellAdd(&pthreadList,&pthreadInfo->node); pthreadInfo->isOnThreadList = 1; status = pthread_mutex_unlock(&listLock); checkStatusQuit(status,"pthread_mutex_unlock","start_routine"); (*pthreadInfo->createFunc)(pthreadInfo->createArg); epicsExitCallAtThreadExits (); free_threadInfo(pthreadInfo); return(0); }
/** * The common code base of waitForMirrorWork and waitForDirectWork. */ Work* MultiWorkQueue::waitForWorkByQueue(HighResolutionStats& newStats, PersonalWorkQueue* personalWorkQueue, AbstractWorkContainer* waitWorkQ, Condition& waitNewWorkCond) { Work* work; SafeMutexLock mutexLock(&mutex); // L O C K HighResolutionStatsTk::addHighResIncStats(newStats, stats); stats.rawVals.busyWorkers--; while(waitWorkQ->getIsEmpty() && likely(personalWorkQueue->getIsWorkListEmpty() ) ) waitNewWorkCond.wait(&mutex); stats.rawVals.busyWorkers++; // personal is always first if(unlikely(!personalWorkQueue->getIsWorkListEmpty() ) ) { // we got something in our personal queue work = personalWorkQueue->getAndPopFirstWork(); } else { work = waitWorkQ->getAndPopNextWork(); numPendingWorks--; } mutexLock.unlock(); // U N L O C K return work; }
void Synchronizer::wakeup() { mutexLock(&mMutex); mShared = 1; conditionVarSignal(&mCondition); mutexUnlock(&mMutex); }
openmittsu::crypto::KeyPair const& KeyRegistry::getClientLongTermKeyPair() const { QMutexLocker mutexLock(&m_mutex); if (!m_isCacheValid) { throw openmittsu::exceptions::InternalErrorException() << "KeyRegistry::getClientLongTermKeyPair() called while the cache is not prepared."; } return m_cachedClientLongTermKeyPair; }
/** * Returns the current player id * @return - player id( 0 - 5 ) */ int ressourcesGetPlayerID() { int result; mutexLock(&clientMutex); result = clientPlayerId; mutexUnLock(&clientMutex); return result; }
bool KeyRegistry::hasIdentity(openmittsu::protocol::ContactId const& identity) const { QMutexLocker mutexLock(&m_mutex); if (!m_isCacheValid) { throw openmittsu::exceptions::InternalErrorException() << "KeyRegistry::hasIdentity(identity = " << identity.toString() << ") called while the cache is invalid."; } return m_cachedPublicKeys.contains(identity); }
/** * Returns the current game stage * @return - game stage ( PLAYER_STAGE_PREPARATION or PLAYER_STAGE_PLAYING ) */ int ressourcesGetStage() { int result; mutexLock(&clientMutex); result = clientStage; mutexUnLock(&clientMutex); return result; }