void passportClerk(int id) { int myLineID = id; //set ID bool firstTime = true; //int firstTime = 1; bool ifBribed; //int ifBribed; //int sizeOfInt = sizeof(int); while(true) { //Wait fot the next cust to signal ifBribed = waitForLine(&passPClerk, id, firstTime); //Set up some convenient variables Lock *workLock = &passPClerk.clerkLock[myLineID]; //int workLock = *(passPClerk.clerkLock + (myLineID * sizeOfInt)); Condition *workCV = &passPClerk.clerkCV[myLineID]; //int workCV = *(passPClerk.clerkCV + (myLineID * sizeOfInt)); //Now the clerk has been woken up and has been told the customer ID //Check int customerSSN = passportClerkCurrentCustomer[myLineID]; //int customerSSN = *(passportClerkCurrentCustomer + (myLineID * sizeOfInt)); cout<<"PassportClerk #" << id << " has received SSN " << customerSSN << " from Customer #" << customerSSN << ".\n"; passportClerkChecked[customerSSN] = customersWithCompletedApps[customerSSN] && customersWithCompletedPics[customerSSN]; //*(passportClerkChecked + (customerSSN * sizeOfInt)) = *(customersWithCompletedApps + (customerSSN * sizeOfInt)) && *(customersWithCompletedPics + (customerSSN * sizeOfInt)); if(!passportClerkChecked[customerSSN]/* *(passportClerkChecked (customerSSN + sizeOfInt)) == 0 */){ cout<<"PassportClerk #"<<id<<" has determined that Customer #"<<customerSSN<< " does not have both their application and picture completed\n"; } else{ cout<<"PassportClerk #"<<id<<" has determined that Customer #"<<customerSSN<< " has both their application and picture completed\n"; } //And Signal workCV->Signal(workLock); //Signal(workCV, workLock); workCV->Wait(workLock); //Wait(workCV, workLock); //Now customer is gone if(passportClerkChecked[customerSSN]/* *(passportClerkChecked + (customerSSN * sizeOfInt)) == 1 */) { cout << "PassportClerk #" << id << " has recorded Customer #" << customerSSN << " passport documentation\n"; } if(ifBribed /*ifBribed == 1*/) { cout<<"PassportClerk #" << id << " has received $500 from Customer #" << customerSSN << ".\n"; passPClerk.cashReceived+=500; } firstTime = false; //firstTime = 0; workLock->Release(); //Release(workLock); } }
bool timed_wait(Lock& lock, boost::uint32_t waitMs) { BOOST_ASSERT(lock.locked()); struct timeval tp = {0}; gettimeofday(&tp, NULL); // Convert from timeval to timespec. struct timespec ts = {0}; ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; // Add waitMs to current time. ts.tv_sec += (waitMs / 1000); boost::uint32_t remainderMs = waitMs % 1000; ts.tv_nsec += (remainderMs * 1000 * 1000); // Check for overflow in tv_nsec. if (ts.tv_nsec >= 1000*1000*1000) { BOOST_ASSERT(ts.tv_nsec < 2*1000*1000*1000); ts.tv_sec += 1; ts.tv_nsec -= 1000*1000*1000; } // POSIX automatically unlocks and locks the mutex. int ret = ::pthread_cond_timedwait(&cond_, &lock.mutex().mutex_, &ts); // Ignore EINVAL. if (ret == ETIMEDOUT) { return false; } return true; }
bool timed_wait(Lock& lock, boost::uint32_t waitMs) { BOOST_ASSERT(lock.locked()); lock.unlock(); { mutex::scoped_lock waitLock(mWaitCountMutex); ++mWaitCount; } DWORD ret = ::WaitForSingleObject(event_, waitMs); assert(ret != WAIT_ABANDONED && ret != WAIT_FAILED); { mutex::scoped_lock waitLock(mWaitCountMutex); --mWaitCount; if (ret != WAIT_TIMEOUT && mWaitCount == 0) { // Set signalled state back to false. ::ResetEvent(event_); } } lock.lock(); if (ret == WAIT_TIMEOUT) { return false; } return true; }
void Jrd::Attachment::initLocks(thread_db* tdbb) { // Take out lock on attachment id const lock_ast_t ast = (att_flags & ATT_system) ? NULL : blockingAstShutdown; Lock* lock = FB_NEW_RPT(*att_pool, 0) Lock(tdbb, sizeof(AttNumber), LCK_attachment, this, ast); att_id_lock = lock; lock->setKey(att_attachment_id); LCK_lock(tdbb, lock, LCK_EX, LCK_WAIT); // Allocate and take the monitoring lock lock = FB_NEW_RPT(*att_pool, 0) Lock(tdbb, sizeof(AttNumber), LCK_monitor, this, blockingAstMonitor); att_monitor_lock = lock; lock->setKey(att_attachment_id); LCK_lock(tdbb, lock, LCK_EX, LCK_WAIT); // Unless we're a system attachment, allocate the cancellation lock if (!(att_flags & ATT_system)) { lock = FB_NEW_RPT(*att_pool, 0) Lock(tdbb, sizeof(AttNumber), LCK_cancel, this, blockingAstCancel); att_cancel_lock = lock; lock->setKey(att_attachment_id); } }
JNIEXPORT jint JNICALL Java_com_kurento_kas_media_tx_MediaTx_putAudioSamples(JNIEnv* env, jclass clazz, jshortArray samples, jint n_samples, jlong time) { int ret; int16_t *samples_buf; mutexAudioTx.lock(); if (!aTxObj) { media_log(MEDIA_LOG_ERROR, LOG_TAG, "No audio-tx initiated"); mutexAudioTx.unlock(); return -1; } samples_buf = (int16_t*)(env->GetShortArrayElements(samples, JNI_FALSE)); try { ret = aTxObj->putAudioSamplesTx(samples_buf, n_samples, time); } catch(MediaException &e) { media_log(MEDIA_LOG_ERROR, LOG_TAG, "%s", e.what()); ret = -1; } env->ReleaseShortArrayElements(samples, samples_buf, 0); mutexAudioTx.unlock(); return ret; }
void addExternalListener(const char *name, int retSize, NetworkAddress *addr) { Event ev; bool isNewEvent = false; lock.lock(); ExternalEvent *extEvent = findEvent(name); if(!extEvent) { extEvent = newEvent(name, retSize); isNewEvent = true; } extEvent->addExternalListener(addr); if(isNewEvent) extEvent->listenerAddr = ev.addListener(name, eventCallback, 0, false, retSize); else { int prevSize = extEvent->retSize; //If ret size larger than previous (singleEvent) retSize, make enough room if(prevSize < retSize) { extEvent->totRetSize = (extEvent->totRetSize/extEvent->retSize)*retSize; extEvent->totRetSize = retSize; } else extEvent->totRetSize += extEvent->retSize; ev.resizeListener(extEvent->listenerAddr, extEvent->totRetSize); } lock.unlock(); }
void wait(Lock& lock) { BOOST_ASSERT(lock.locked()); lock.unlock(); ::WaitForSingleObject(event_, INFINITE); lock.lock(); }
virtual void threadProc() { omsg("ImageLoaderThread: start"); while(!sShutdownLoaderThread) { sImageQueueLock.lock(); if(sImageQueue.size() > 0) { Ref<ImageUtils::LoadImageAsyncTask> task = sImageQueue.front(); sImageQueue.pop(); sImageQueueLock.unlock(); Ref<PixelData> res = ImageUtils::loadImage(task->getData().path, task->getData().isFullPath); if(!sShutdownLoaderThread) { task->getData().image = res; task->notifyComplete(); } //sImageQueueLock.unlock(); } else { sImageQueueLock.unlock(); } osleep(100); } omsg("ImageLoaderThread: shutdown"); }
HRESULT Filter::Stop() { //Stop is a synchronous operation: when it completes, //the filter is stopped. //odbgstream os; Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //odbgstream os; //os << "mkvsplit::Filter::Stop" << endl; switch (m_state) { case State_Paused: case State_Running: m_state = State_Stopped; OnStop(); //decommit outpin's allocator break; case State_Stopped: default: break; } return S_OK; }
bool context_node::open(bool access_rw, bool* fsetxattr_failed) { lock_.lock(); if (pa_) { lock_.unlock(); return true; } char filename[PROP_FILENAME_MAX]; int len = snprintf(filename, sizeof(filename), "%s/%s", property_filename, context_); if (len < 0 || len > PROP_FILENAME_MAX) { lock_.unlock(); return false; } if (access_rw) { pa_ = map_prop_area_rw(filename, context_, fsetxattr_failed); } else { pa_ = map_prop_area(filename #if MB_ENABLE_COMPAT_PROPERTIES , false #endif ); } lock_.unlock(); return pa_; }
HRESULT Filter::Run(REFERENCE_TIME start) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; #ifdef _DEBUG odbgstream os; os << "webmvorbisencoder::Filter::Run" << endl; #endif switch (m_state) { case State_Stopped: OnStart(); break; case State_Paused: case State_Running: default: break; } m_start = start; m_state = State_Running; return S_OK; }
void Lock::printOutCircularDeadLock(Thread* starting) { debug(LOCK, "CIRCULAR DEADLOCK when waiting for %s (%p) with thread %s (%p)!\n", getName(), this, currentThread->getName(), currentThread); debug(LOCK, "Printing out the circular deadlock:\n"); currentThread->lock_waiting_on_ = this; // in this case we can access the other threads, because we KNOW that they are indirectly waiting on the current thread. for(Thread* thread = starting; thread != 0; thread = thread->lock_waiting_on_->held_by_) { Thread * holding = thread->lock_waiting_on_->held_by_; Lock* lock = thread->lock_waiting_on_; debug(LOCK, "Thread %-40.40s (%p) holding lock %-40.40s (%p), waiting for lock %-40.40s (%p)\n", holding->getName(), holding, lock->getName(), lock, holding->lock_waiting_on_->getName(), holding->lock_waiting_on_); if(kernel_debug_info) { debug(LOCK, "This lock has been locked at "); kernel_debug_info->printCallInformation(lock->last_accessed_at_); } // In the thread we are looking at is the current one, we have to stop. // It would result in an endless loop (circular print out ^^). if(thread == currentThread) break; } }
HRESULT Filter::EnumPins(IEnumPins** pp) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; const ULONG outpins_count = static_cast<ULONG>(m_outpins.size()); const ULONG n = 1 + outpins_count; //odbgstream os; //os << "WebmSplit::filter::enumpins: n=" << n << endl; const size_t cb = n * sizeof(IPin*); IPin** const pins = (IPin**)_alloca(cb); IPin** pin = pins; *pin++ = &m_inpin; typedef outpins_t::iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); while (i != j) *pin++ = *i++; return CEnumPins::CreateInstance(pins, n, pp); }
HRESULT Filter::Pause() { //Unlike Stop(), Pause() can be asynchronous (that's why you have //GetState()). We could use that here to build the samples index. Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //odbgstream os; //os << "WebmSplit::Filter::Pause" << endl; switch (m_state) { case State_Stopped: OnStart(); break; case State_Running: case State_Paused: default: break; } m_state = State_Paused; return S_OK; }
HRESULT Filter::Stop() { // Stop is a synchronous operation: when it completes, // the filter is stopped. Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; // odbgstream os; // os << "mkvsplit::Filter::Stop" << endl; switch (m_state) { case kStatePaused: case kStatePausedWaitingForKeyframe: case kStateRunning: case kStateRunningWaitingForKeyframe: m_state = kStateStopped; OnStop(); // decommit outpin's allocator break; case kStateStopped: break; default: assert(false); break; } return S_OK; }
HRESULT Filter::Pause() { //Unlike Stop(), Pause() can be asynchronous (that's why you have //GetState()). Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //odbgstream os; //os << "mkvsplit::Filter::Pause" << endl; switch (m_state) { case State_Stopped: OnStart(); //commit outpin's allocator break; case State_Running: case State_Paused: default: break; } m_state = State_Paused; return S_OK; }
void getErrorDescription(int errorCode, WCHAR *buffer, int len) { static Lock lock; lock.lock(); LPVOID lpMsgBuf; FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorCode, 0, // Default language (LPWSTR) &lpMsgBuf, 0, NULL ); _snwprintf(buffer, len, L"Error %d : %s", errorCode, (LPCTSTR)lpMsgBuf); int len1 = wcslen(buffer); if (len1 >= 2) { buffer[len1 - 2] = '\0'; } LocalFree( lpMsgBuf ); lock.unlock(); }
HRESULT Filter::Run(REFERENCE_TIME start) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //odbgstream os; //os << "mkvsplit::Filter::Run" << endl; switch (m_state) { case State_Stopped: OnStart(); break; case State_Paused: case State_Running: default: break; } m_start = start; m_state = State_Running; return S_OK; }
HRESULT Filter::JoinFilterGraph( IFilterGraph *pGraph, LPCWSTR name) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //NOTE: //No, do not adjust reference counts here! //Read the docs for the reasons why. //ENDNOTE. m_info.pGraph = pGraph; if (name == 0) m_info.achName[0] = L'\0'; else { enum { size = sizeof(m_info.achName)/sizeof(WCHAR) }; const errno_t e = wcscpy_s(m_info.achName, size, name); e; assert(e == 0); //TODO } return S_OK; }
bool wait_for_usec(Lock& lock, long usec) { ASIO_ASSERT(lock.locked()); if ((state_ & 1) == 0) { state_ += 2; timespec ts; #if (defined(__MACH__) && defined(__APPLE__)) \ || (defined(__ANDROID__) && (__ANDROID_API__ < 21)) ts.tv_sec = usec / 1000000; ts.tv_nsec = (usec % 1000000) * 1000; ::pthread_cond_timedwait_relative_np( &cond_, &lock.mutex().mutex_, &ts); // Ignore EINVAL. #else // (defined(__MACH__) && defined(__APPLE__)) // || (defined(__ANDROID__) && (__ANDROID_API__ < 21)) if (::clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { ts.tv_sec += usec / 1000000; ts.tv_nsec = (usec % 1000000) * 1000; ts.tv_sec += ts.tv_nsec / 1000000000; ts.tv_nsec = ts.tv_nsec % 1000000000; ::pthread_cond_timedwait(&cond_, &lock.mutex().mutex_, &ts); // Ignore EINVAL. } #endif // (defined(__MACH__) && defined(__APPLE__)) // || (defined(__ANDROID__) && (__ANDROID_API__ < 21)) state_ -= 2; } return (state_ & 1) != 0; }
void signal_and_unlock(Lock& lock) { BOOST_ASSERT(lock.locked()); signalled_ = true; lock.unlock(); ::pthread_cond_signal(&cond_); // Ignore EINVAL. }
void signal_and_unlock(Lock& lock) { BOOST_ASIO_ASSERT(lock.locked()); signalled_ = true; lock.unlock(); cond_.notify_one(); }
JNIEXPORT jint JNICALL Java_com_kurento_kas_media_tx_MediaTx_putVideoFrame(JNIEnv* env, jclass clazz, jbyteArray frame, jint width, jint height, jlong time) { int ret; uint8_t* frame_buf; if (!vTxObj) { media_log(MEDIA_LOG_ERROR, LOG_TAG, "No video-tx initiated"); mutexVideoTx.unlock(); return -1; } ret = 0; frame_buf = (uint8_t*)(env->GetByteArrayElements(frame, JNI_FALSE)); try { ret = vTxObj->putVideoFrameTx(frame_buf, width, height, time); } catch(MediaException &e) { media_log(MEDIA_LOG_ERROR, LOG_TAG, "%s", e.what()); ret = -1; } env->ReleaseByteArrayElements(frame, (jbyte*)frame_buf, JNI_ABORT); mutexVideoTx.unlock(); return ret; }
virtual void threadProc() { omsg("MeshLoaderThread: start"); while(!sShutdownLoaderThread) { if(sMeshQueue.size() > 0) { sMeshQueueLock.lock(); if(sMeshQueue.size() > 0) { Ref<WarpMeshUtils::LoadWarpMeshGridAsyncTask> task = sMeshQueue.front(); sMeshQueue.pop(); sMeshQueueLock.unlock(); Ref<WarpMeshGrid> mesh = WarpMeshUtils::loadWarpMeshGrid(task->getData().path, task->getData().isFullPath); if(!sShutdownLoaderThread) { task->getData().mesh = mesh; task->notifyComplete(); } } else { sMeshQueueLock.unlock(); } } osleep(100); } omsg("MeshLoaderThread: shutdown"); }
//##ModelId=424BB64700A6 void ACDX::setAliasAvailable(CString _epid, CString _callid) { std::list<Agent>::iterator agentElment; Agent _agent; Agent agent = agentByCallId(_epid, _callid); // find first alias while ((agent.isOK) && (_callid.GetLength() > 0)) { // in alias list update element for(agentElment = aliasList.begin(); agentElment != aliasList.end();agentElment++) { _agent = *agentElment; if (agent.getAlias()==_agent.getAlias()) { if (g_lock.lock()) { agentElment->setState(Alias::AVAILABLE); agentElment->setLastCall(); agentElment->setLastTime(); agentElment->setCallId(""); backlog->checkPending((&(Agent)*agentElment),aliasList); //------> need test it agent in checkpending g_lock.unlock(); }// if lock }//if alias == }// for // check if we have pending calls for this now available agent //backlog->checkPending(&agent); //------> need test it agent in checkpending agent = agentByCallId(_epid, _callid); // find next alias } }
Lock* LockManager::searchLockCycle(Lock* newLock) { Thread *thread = ThreadManager::getInstance().at(GET_CURRENT_THREAD_ID()); if (!thread) { return nullptr; } std::vector<Lock*>trace; trace.push_back(newLock); Lock *deadLock = nullptr; while (true) { Lock threadLock = thread->lock(); if (threadLock == nullptr) { break; } if (threadLock->lockID() == trace[0]->lockID()) { deadLock = threadLock; break; } trace.push_back(threadLock); thread = ThreadManager::getInstance().at(threadLock->threadId()); if (!thread) { break; } trace.empty(); return deadLock; } }
void wait(Lock& lock) { // POSIX automatically unlocks and locks the mutex. BOOST_ASSERT(lock.locked()); ::pthread_cond_wait(&cond_, &lock.mutex().mutex_); // Ignore EINVAL. }
LockSafeScope::LockSafeScope(Lock* lock, LPCWSTR fileName, int lineNo) { if (lock == nullptr) { return; } if (_shutdown == true) { return; } lock_ = lock; Lock *deadLock = LockManager::getInstance().checkDaeadLock(lock_); if (deadLock != nullptr) { #ifdef STERN_MODE SErrLog(L"<%s>lock , <%s>lock is dead", deadLock->name(), lock->name()); #else std::lock(lock_ -> mutex(), deadLock->mutex()); #endif return; } lock_->lock*(fileName, lineNo); lock->setThreadID(GET_CURRENT_THREAD_ID()); }
void wait(Lock& lock) { BOOST_ASSERT(lock.locked()); lock.unlock(); { mutex::scoped_lock waitLock(mWaitCountMutex); ++mWaitCount; } ::WaitForSingleObject(event_, INFINITE); { mutex::scoped_lock waitLock(mWaitCountMutex); --mWaitCount; if (mWaitCount == 0) { // Set signalled state back to false. ::ResetEvent(event_); } } lock.lock(); }
template <typename Lock> void wait(Lock &lock) { # ifndef NDEBUG if(!lock.owns_lock()) throw_condition_error(); # endif wait(*const_cast<mutex*>(lock.mutex())); }