UtlBoolean handleMessage(OsMsg& rMsg) { int waitMsec = rand(); delay((waitMsec % 3 ) * 50); OsEvent* event = ((OsRpcMsg&)rMsg).getEvent(); CPPUNIT_ASSERT(event); mNumEvents++; int eventIndex =-1; event->getUserData(eventIndex); //CPPUNIT_ASSERT(mNumEvents == eventIndex); CPPUNIT_ASSERT(mNumEvents < mMaxEvents); OsStatus eventStat = event->signal(mNumEvents); if(eventStat == OS_ALREADY_SIGNALED) { // The Right side lost, the Left side is done // we delete on this side delete event; event = NULL; mpDeletedEvent[mNumEvents] = TRUE; } else { // This/Right side won. we do nothing mpDeletedEvent[mNumEvents] = FALSE; //osPrintf("Right: %d\n", eventStat); } return(TRUE); }
// Disarm the timer OsStatus OsTimer::stop(UtlBoolean synchronous) { #ifndef NDEBUG CHECK_VALIDITY(this); #endif OsStatus result; UtlBoolean sendMessage = FALSE; // Update members. { OsLock lock(mBSem); #ifndef NDEBUG assert(!mDeleting); #endif // Determine whether the call is successful. if (isStarted(mApplicationState)) { mWasFired = FALSE; // Update state to stopped. mApplicationState++; result = OS_SUCCESS; if (mOutstandingMessages == 0) { // We will send a message. sendMessage = TRUE; mOutstandingMessages++; } } else { result = OS_FAILED; } } // If we need to, send an UPDATE message to the timer task. if (sendMessage) { if (synchronous) { // Send message and wait. OsEvent event; OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE_SYNC, this, &event); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); event.wait(); } else { // Send message. OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE, this, NULL); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); } } return result; }
// Handle an incoming message // Return TRUE if the message was handled, otherwise FALSE. UtlBoolean MpMediaTask::handleMessage(OsMsg& rMsg) { UtlBoolean handled; MpFlowGraphBase* pFlowGraph; MpMediaTaskMsg* pMsg; if (rMsg.getMsgType() != OsMsg::MP_TASK_MSG) return FALSE; // the method only handles MP_TASK_MSG messages pMsg = (MpMediaTaskMsg*) &rMsg; pFlowGraph = (MpFlowGraphBase*) pMsg->getPtr1(); handled = TRUE; // until proven otherwise, assume we'll handle the msg switch (pMsg->getMsg()) { case MpMediaTaskMsg::MANAGE: { OsEvent* event = (OsEvent*)pMsg->getPtr2(); if (!handleManage(pFlowGraph)) mHandleMsgErrs++; if (event) event->signal(0); break; } case MpMediaTaskMsg::SET_FOCUS: if (!handleSetFocus(pFlowGraph)) mHandleMsgErrs++; break; case MpMediaTaskMsg::START: if (!handleStart(pFlowGraph)) mHandleMsgErrs++; break; case MpMediaTaskMsg::STOP: if (!handleStop(pFlowGraph)) mHandleMsgErrs++; break; case MpMediaTaskMsg::UNMANAGE: { OsEvent* event = (OsEvent*)pMsg->getPtr2(); if (!handleUnmanage(pFlowGraph)) mHandleMsgErrs++; if (event) event->signal(0); break; } case MpMediaTaskMsg::WAIT_FOR_SIGNAL: if (!handleWaitForSignal(pMsg)) mHandleMsgErrs++; break; default: handled = FALSE; // we didn't handle the message after all break; } return handled; }
// Directs the media processing task to remove the flow graph from its // set of managed flow graphs. // If the flow graph is not already in the MpFlowGraphBase::STOPPED state, // then the flow graph will be stopped before it is removed from the set // of managed flow graphs. // Returns OS_SUCCESS to indicate that the media task will stop managing // the indicated flow graph at the start of the next frame processing // interval. OsStatus MpMediaTask::unmanageFlowGraph(MpFlowGraphBase& rFlowGraph) { OsEvent event; MpMediaTaskMsg msg(MpMediaTaskMsg::UNMANAGE, &rFlowGraph, &event); OsStatus res; res = postMessage(msg, OsTime::NO_WAIT_TIME); assert(res == OS_SUCCESS); // wait until flowgraph is unmanaged event.wait(); return OS_SUCCESS; }
// Destructor OsTimerTask::~OsTimerTask() { if (sInstance.isStarted()) { // Shut down the task. OsEvent event; OsTimerTaskCommandMsg msg(OsTimerTaskCommandMsg::OS_TIMER_SHUTDOWN, NULL, &event); // Send the OS_TIMER_SHUTDOWN message. OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); // Wait for the response. event.wait(); } }
void testThreadedMultipleFire() { OsEvent event; MultipleFireThread fireThread(-1, &event); fireThread.start(); for (int i=0; i<10000; i++) { CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, event.wait(500)); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, event.reset()); } fireThread.requestShutdown(); }
int ClientTask::run(void* runArg) { OsEvent* pEvent = (OsEvent*)runArg; OsStatus status; fileExecute(InputFile, false); do { //printf("%s is signaling\n", mName.data()); status = pEvent->signal(1); } while (status == OS_ALREADY_SIGNALED); return 0; }
// Destructor OsTimer::~OsTimer() { #ifndef NDEBUG CHECK_VALIDITY(this); #endif // Update members and determine whether we need to send an UPDATE_SYNC // to stop the timer or ensure that the timer task has no queued message // about this timer. UtlBoolean sendMessage = FALSE; { OsLock lock(mBSem); #ifndef NDEBUG assert(!mDeleting); // Lock out all further application methods. mDeleting = TRUE; #endif // Check if the timer needs to be stopped. if (isStarted(mApplicationState)) { sendMessage = TRUE; mApplicationState++; } // Check if there are outstanding messages that have to be waited for. if (mOutstandingMessages > 0) { sendMessage = TRUE; } // If we have to send a message, make note of it. if (sendMessage) { mOutstandingMessages++; } } // Send a message to the timer task if we need to. if (sendMessage) { OsEvent event; OsTimerMsg msg(OsTimerMsg::OS_TIMER_UPDATE_SYNC, this, &event); OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); event.wait(); } // If mbManagedNotifier, free *mpNotifier. if (mbManagedNotifier) { delete mpNotifier; } }
// Destroy the singleton instance of the timer task. void OsTimerTask::destroyTimerTask(void) { OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTimerTask::destroyTimerTask entered"); if (sInstance.isStarted()) { OsEvent event; OsTimerTaskCommandMsg msg(OsTimerTaskCommandMsg::OS_TIMER_SHUTDOWN, NULL, &event); // Send the OS_TIMER_SHUTDOWN message. OsStatus res = OsTimerTask::getTimerTask()->postMessage(msg); assert(res == OS_SUCCESS); // Wait for the response. event.wait(); } }
// Directs the media processing task to add the flow graph to its // set of managed flow graphs. The flow graph must be in the // MpFlowGraphBase::STOPPED state when this method is invoked. // Returns OS_INVALID_ARGUMENT if the flow graph is not in the STOPPED state. // Otherwise returns OS_SUCCESS to indicate that the flow graph will be added // to the set of managed flow graphs at the start of the next frame // processing interval. OsStatus MpMediaTask::manageFlowGraph(MpFlowGraphBase& rFlowGraph) { OsEvent event; MpMediaTaskMsg msg(MpMediaTaskMsg::MANAGE, &rFlowGraph, &event); OsStatus res; if (rFlowGraph.getState() != MpFlowGraphBase::STOPPED) { // PRINTF("MpMediaTask::manageFlowGraph: error!\n", 0,0,0,0,0,0); return OS_INVALID_ARGUMENT; } res = postMessage(msg, OsTime::NO_WAIT_TIME); assert(res == OS_SUCCESS); // wait until flowgraph is managed event.wait(); return OS_SUCCESS; }
void testTimedEvent() { OsTime eventTimeout(2,0); OsEvent* pEvent; pEvent = new OsEvent(12345); time_t epochTime = time(NULL); CPPUNIT_ASSERT(pEvent->wait(eventTimeout) != OS_SUCCESS); pEvent->signal(67890); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, pEvent->wait(eventTimeout)); pEvent->reset(); CPPUNIT_ASSERT(pEvent->wait(eventTimeout) != OS_SUCCESS); epochTime = time(NULL) - epochTime; // Make sure we waited (approximately) 2 seconds each time. CPPUNIT_ASSERT(epochTime > 2 && epochTime < 6); delete pEvent; }
void testThreadedEvent() { // Seed the random number generator srand(OsDateTime::getSecsSinceEpoch()); int numTries = 100; int* rightResults = new int[numTries]; int* leftResults = new int[numTries]; // Create the Right thread. This context will be the // Left thread. RightEventThread rightThread(rightResults, numTries); rightThread.start(); int index; for(index = 0; index < numTries; index++) { OsEvent* event = new OsEvent(index); OsRpcMsg eventMsg(OsMsg::USER_START,0,*event); rightThread.postMessage(eventMsg); int waitTimeMsec = (rand() % 3) * 110; OsTime time(0, waitTimeMsec * 1000); event->wait(time); OsStatus eventStat = event->signal(index); if(eventStat == OS_ALREADY_SIGNALED) { // We (Left) lost the other side is done int eventData; event->getEventData(eventData); CPPUNIT_ASSERT(eventData == index); // This/Left side deletes the event delete event; event = NULL; leftResults[index] = TRUE; } else { // The other/Right side lost // Do nothing leftResults[index] = FALSE; //osPrintf("Left: %d\n", eventStat); } } OsTask::delay(1000); int leftDeletes = 0; int rightDeletes = 0; for(index = 0; index < numTries; index++) { if(leftResults[index] == TRUE) { leftDeletes++; } if(rightResults[index] == TRUE) { rightDeletes++; } if(rightResults[index] == leftResults[index]) { //osPrintf("Left deleted: %d Right deleted: %d\n", // leftDeletes, rightDeletes); //osPrintf("[%d]: Both sides %s\n", index, // rightResults[index] ? "Deleted" : "Did not delete"); } CPPUNIT_ASSERT(rightResults[index] != leftResults[index]); } //osPrintf("Left deleted: %d Right deleted: %d\n", // leftDeletes, rightDeletes); CPPUNIT_ASSERT(leftDeletes + rightDeletes == numTries); }
// Realizes the player by initiating a connection to the target, allocates // buffers, etc. OsStatus MpStreamPlayer::realize(UtlBoolean bBlock /* = TRUE */) { OsStatus status = OS_FAILED ; OsEvent eventHandle ; intptr_t eventData ; // Only proceed if we have a flow graph and the player is unrealized. if (getState() == PlayerUnrealized) { // Create an mpQueueEvent object to signal state changes in from // the MpStreamFeeder mpQueueEvent = new OsQueuedEvent(*getMessageQueue(), 0); // Realize the stream if (mSourceType == SourceUrl) { if (mpMsgQ != NULL) { MpStreamMsg msg(MpStreamMsg::STREAM_REALIZE_URL, mTarget, NULL, &eventHandle, mpQueueEvent, mFlags, (intptr_t) new Url(mUrl)) ; status = mpMsgQ->send(msg) ; } } else if (mSourceType == SourceBuffer) { if (mpMsgQ != NULL) { MpStreamMsg msg(MpStreamMsg::STREAM_REALIZE_BUFFER, mTarget, NULL, &eventHandle, mpQueueEvent, mFlags, (intptr_t) mpBuffer) ; status = mpMsgQ->send(msg) ; } } if (status == OS_SUCCESS) { // Wait for a response status = eventHandle.wait(OsTime(MAX_REALIZE_WAIT, 0)) ; if (status == OS_SUCCESS) { if (eventHandle.getEventData(eventData) == OS_SUCCESS) { mHandle = (StreamHandle) eventData ; if (mHandle != 0) mbRealized = TRUE ; } else { mHandle = NULL ; } } else { mHandle = NULL ; } } } if (mHandle == 0) { mState = PlayerDestroyed ; status = OS_FAILED ; mSemStateChange.release() ; } if (status == OS_SUCCESS) { // Start Server task if successfull if (start() == TRUE) { // Block while waiting for prefetch (if requested) if (bBlock) { while (getState() == PlayerUnrealized) { mSemStateChange.acquire(); } } else { // Wait for task to startup while (!isStarted()) { OsTask::yield() ; } } } else { syslog(FAC_STREAMING, PRI_CRIT, "Failed to create thread for MpStreamPlayer") ; // Unable to create thread; attempt to clean up status = OS_FAILED ; MpStreamMsg msgStop(MpStreamMsg::STREAM_STOP, mTarget, mHandle); mpMsgQ->send(msgStop) ; MpStreamMsg msgDestroy(MpStreamMsg::STREAM_DESTROY, mTarget, mHandle); mpMsgQ->send(msgDestroy) ; // YIKES: This is hard to recover from, we don't have a message queue // to wait for a response from the lower layers. If someone deletes // this immediately after this call, the lower layers could choke // on a now-deleted mpQueueEvent. There are two options that I can // think of: 1) garbage collect the player after some long period of // time, 2) block the thread context for some reasonable amount of // time. I'm going with #2 for now... OsTask::delay(1000) ; mbRealized = FALSE ; mState = PlayerDestroyed ; mSemStateChange.release() ; } } return status ; }
UtlBoolean SipProtocolServerBase::waitForClientToWrite(SipClient* client) { UtlBoolean exists; UtlBoolean busy = FALSE; int numTries = 0; do { numTries++; mClientLock.acquireWrite(); exists = clientExists(client); if(exists) { busy = client->isInUseForWrite(); if(!busy) { client->markInUseForWrite(); mClientLock.releaseWrite(); if(numTries > 1) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::waitForClientToWrite %p locked after %d tries", mProtocolString.data(), client, numTries); } } else { // We set an event to be signaled when a // transaction is released. OsEvent* waitEvent = new OsEvent(); client->notifyWhenAvailableForWrite(*waitEvent); // Must unlock while we wait or there is a dead lock mClientLock.releaseWrite(); #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::waitForClientToWrite %p " "waiting on: %p after %d tries", mProtocolString.data(), client, waitEvent, numTries); #endif // Do not block forever OsTime maxWaitTime(0, 500000); // If the other side signaled if(waitEvent->wait(maxWaitTime) == OS_SUCCESS) { // The other side is no longer referencing // the event. This side must clean it up delete waitEvent; waitEvent = NULL; } // A timeout occurred and the other side did not signal yet else { // Signal the other side to indicate we are done // with the event. If already signaled, we lost // a race and the other side was done first. if(waitEvent->signal(0) == OS_ALREADY_SIGNALED) { delete waitEvent; waitEvent = NULL; } } #ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "Sip%sServerBase::waitForClientToWrite %p done waiting after %d tries", mProtocolString.data(), client, numTries); #endif } } else { mClientLock.releaseWrite(); OsSysLog::add(FAC_SIP, PRI_ERR, "Sip%sServerBase::waitForClientToWrite %p gone after %d tries", mProtocolString.data(), client, numTries); } } while(exists && busy); return(exists && !busy); }
// Realizes the player by initiating a connection to the target, allocates // buffers, etc. OsStatus MpStreamPlaylistPlayer::realize(UtlBoolean bBlock) { OsStatus status = OS_FAILED; PlayListEntry* e; if (mAggregateState == PlayerFailed) { OsSysLog::add(FAC_MP, PRI_ERR, "MpStreamPlaylistPlayer::realize failure, mAggregateState == PlayerFailed"); return status; } // Start prefetching all of the elements UtlSListIterator playListDbIterator(*mPlayListDb) ; while((e = (PlayListEntry*)playListDbIterator())) { // OsSysLog::add(FAC_MP, PRI_DEBUG, "MpStreamPlaylistPlayer::realize entry[%d] state %d", e->index, e->state); if (e->state == PlayerUnrealized) { OsEvent eventHandle; // Realize the stream if (e->sourceType == SourceUrl) { MpStreamMsg msg(MpStreamMsg::STREAM_REALIZE_URL, mTarget, NULL, &eventHandle, e->pQueuedEvent, e->flags, (intptr_t) new Url(e->url)); status = mpMsgQ->send(msg); if (status != OS_SUCCESS) { setEntryState(e, PlayerFailed); e->handle = NULL; OsSysLog::add(FAC_MP, PRI_ERR, "MpStreamPlaylistPlayer::realize failed on send of MpStreamMsg::STREAM_REALIZE_URL message"); } } else if (e->sourceType == SourceBuffer) { MpStreamMsg msg(MpStreamMsg::STREAM_REALIZE_BUFFER, mTarget, NULL, &eventHandle, e->pQueuedEvent, e->flags, (intptr_t) e->pBuffer); status = mpMsgQ->send(msg); if (status != OS_SUCCESS) { setEntryState(e, PlayerFailed); e->handle = NULL; delete e->pBuffer; e->pBuffer = NULL; OsSysLog::add(FAC_MP, PRI_ERR, "MpStreamPlaylistPlayer::realize failed on send of MpStreamMsg::STREAM_REALIZE_BUFFER message"); } } if (status == OS_SUCCESS) { // Wait for a response intptr_t eventData; status = eventHandle.wait(mRealizeTimeout); if (status == OS_SUCCESS) status = eventHandle.getEventData(eventData); if (status == OS_SUCCESS) { e->handle = (StreamHandle) eventData; } else { setEntryState(e, PlayerFailed); e->handle = NULL; if (e->sourceType == SourceBuffer) { delete e->pBuffer; e->pBuffer = NULL; } OsSysLog::add(FAC_MP, PRI_ERR, "MpStreamPlaylistPlayer::realize STREAM_REALIZE_ request failed"); } } } } // Block if requested playListDbIterator.reset(); if ((status == OS_SUCCESS) && bBlock) { while((e = (PlayListEntry*)playListDbIterator()) != NULL && (mAggregateState != PlayerFailed)) { while (e->state == PlayerUnrealized) { status = mSemStateChange.acquire(mRealizeTimeout); if (status == OS_WAIT_TIMEOUT) { setEntryState(e, PlayerFailed); OsSysLog::add(FAC_MP, PRI_ERR, "MpStreamPlaylistPlayer::realize timed out waiting for Realize to complete"); break; } } } } return status; }
UtlBoolean SipTransactionList::waitUntilAvailable(SipTransaction* transaction, const UtlString& hash) { UtlBoolean exists; UtlBoolean busy = FALSE; int numTries = 0; do { numTries++; lock(); exists = transactionExists(transaction, hash); if(exists) { busy = transaction->isBusy(); if(!busy) { transaction->markBusy(); unlock(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p locked after %d tries\n", transaction, numTries); //#endif } else { // We set an event to be signaled when a // transaction is released. OsEvent* waitEvent = new OsEvent; transaction->notifyWhenAvailable(waitEvent); // Must unlock while we wait or there is a dead lock unlock(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p waiting on: %p after %d tries\n", transaction, waitEvent, numTries); //#endif OsStatus waitStatus; OsTime transBusyTimeout(1, 0); int waitTime = 0; do { if(waitTime > 0) OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable %p still waiting: %d", transaction, waitTime); waitStatus = waitEvent->wait(transBusyTimeout); waitTime+=1; } while(waitStatus != OS_SUCCESS && waitTime < 30); // If we were never signaled, then we signal the // event so the other side knows that it has to // free up the event if(waitEvent->signal(-1) == OS_ALREADY_SIGNALED) { delete waitEvent; waitEvent = NULL; } // If we bailed out before the event was signaled // pretend the transaction does not exist. if(waitStatus != OS_SUCCESS) { exists = FALSE; } if(waitTime > 1) { if (OsSysLog::willLog(FAC_SIP, PRI_WARNING)) { UtlString transTree; UtlString waitingTaskName; OsTask* waitingTask = OsTask::getCurrentTask(); if(waitingTask) waitingTaskName = waitingTask->getName(); transaction->dumpTransactionTree(transTree, FALSE); OsSysLog::add(FAC_SIP, PRI_WARNING, "SipTransactionList::waitUntilAvailable status: %d wait time: %d transaction: %p task: %s transaction tree: %s", waitStatus, waitTime, transaction, waitingTaskName.data(), transTree.data()); } } //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p done waiting after %d tries\n", transaction, numTries); //#endif } } else { unlock(); //#ifdef TEST_PRINT OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipTransactionList::waitUntilAvailable %p gone after %d tries\n", transaction, numTries); //#endif } } while(exists && busy); return(exists && !busy); }
int main() #endif { #ifdef TEST UtlMemCheck* pMemCheck = 0; pMemCheck = new UtlMemCheck(); // checkpoint for memory leak check #endif //TEST cout << "Entering main()" << endl; /* ============================ Testing Start ============================= */ /* ============================ OsProcess ==================================== */ #if defined(_WIN32) || defined(__pingtel_on_posix__) //vxworks wont use these classes osPrintf("Starting Process test...\n"); //Text Process Class if (TestProcessClass() != OS_SUCCESS) osPrintf("TestProcessterator FAILED!\n"); //Test Process Iterator if (TestProcessIterator() != OS_SUCCESS) osPrintf("TestProcessterator FAILED!\n"); //Test Process Manager methods if (TestProcessMgr() != OS_SUCCESS) osPrintf("TestProcessterator FAILED!\n"); osPrintf("Finished Process test.\n"); #endif /* ============================ OsTime ==================================== */ OsTime* pTime; pTime = new OsTime(); delete pTime; /* ============================ OsMutex =================================== */ OsMutex* pMutex; pMutex = new OsMutex(0); delete pMutex; /* ============================ OsBSem ==================================== */ OsBSem* pBSem; pBSem = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); assert(pBSem->acquire() == OS_SUCCESS); assert(pBSem->tryAcquire() == OS_BUSY); assert(pBSem->release() == OS_SUCCESS); delete pBSem; /* ============================ OsCSem ==================================== */ OsCSem* pCSem; // the initial count on the semaphore will be 2 pCSem = new OsCSem(OsCSem::Q_PRIORITY, 2); assert(pCSem->acquire() == OS_SUCCESS); // take it once assert(pCSem->acquire() == OS_SUCCESS); // take it twice assert(pCSem->tryAcquire() == OS_BUSY); assert(pCSem->release() == OS_SUCCESS); // release once assert(pCSem->release() == OS_SUCCESS); // release twice delete pCSem; /* ============================ OsLock ==================================== */ // Create a binary semaphore for use with an OsLock object pBSem = new OsBSem(OsBSem::Q_PRIORITY, OsBSem::FULL); // Acquire semaphore at the start of the method, release it on exit guardedWithBSem(*pBSem); delete pBSem; /* ============================ OsRWMutex ================================= */ OsRWMutex* pRWMutex; pRWMutex = new OsRWMutex(OsRWMutex::Q_FIFO); assert(pRWMutex->acquireRead() == OS_SUCCESS); assert(pRWMutex->tryAcquireWrite() == OS_BUSY); assert(pRWMutex->releaseRead() == OS_SUCCESS); assert(pRWMutex->tryAcquireWrite() == OS_SUCCESS); assert(pRWMutex->tryAcquireRead() == OS_BUSY); assert(pRWMutex->releaseWrite() == OS_SUCCESS); delete pRWMutex; /* ============================ OsReadLock and OsWriteLock ================ */ // Create an OsRWMutex for use with OsReadLock and OsWriteLock objects pRWMutex = new OsRWMutex(OsRWMutex::Q_FIFO); // Acquire read lock at the start of the method, release it on exit guardedForReading(*pRWMutex); // Acquire write lock at the start of the method, release it on exit guardedForWriting(*pRWMutex); delete pRWMutex; /* ============================ OsNameDb ================================== */ OsNameDb* pNameDb; int storedInt; pNameDb = OsNameDb::getNameDb(); assert(pNameDb->isEmpty()); assert(pNameDb->numEntries() == 0); assert(pNameDb->insert("test1", 1) == OS_SUCCESS); assert(pNameDb->insert("test1", 2) == OS_NAME_IN_USE); assert(!pNameDb->isEmpty()); assert(pNameDb->numEntries() == 1); assert(pNameDb->insert("test2", 2) == OS_SUCCESS); assert(pNameDb->numEntries() == 2); assert(pNameDb->lookup("test1", NULL) == OS_SUCCESS); assert(pNameDb->lookup("test1", &storedInt) == OS_SUCCESS); assert(storedInt == 1); assert(pNameDb->lookup("test2", &storedInt) == OS_SUCCESS); assert(storedInt == 2); assert(pNameDb->lookup("test3", NULL) == OS_NOT_FOUND); pNameDb->remove("test1"); pNameDb->remove("test2"); delete pNameDb; /* ============================ OsMsgQ ==================================== */ OsMsgQ* pMsgQ1; OsMsg* pMsg1; OsMsg* pMsg2; OsMsg* pRecvMsg; pMsgQ1 = new OsMsgQ(OsMsgQ::DEF_MAX_MSGS, OsMsgQ::DEF_MAX_MSG_LEN, OsMsgQ::Q_PRIORITY, "MQ1"); pMsg1 = new OsMsg(OsMsg::UNSPECIFIED, 0); pMsg2 = new OsMsg(OsMsg::UNSPECIFIED, 0); assert(pMsgQ1->isEmpty()); assert(pMsgQ1->numMsgs() == 0); assert(pMsgQ1->getSendHook() == NULL); pMsgQ1->setSendHook(msgSendHook); assert(pMsgQ1->getSendHook() == msgSendHook); OsStatus stat = pMsgQ1->send(*pMsg1); assert(stat == OS_SUCCESS); assert(!pMsgQ1->isEmpty()); assert(pMsgQ1->numMsgs() == 1); stat = pMsgQ1->send(*pMsg2); assert(stat == OS_SUCCESS); assert(pMsgQ1->numMsgs() == 2); stat = pMsgQ1->receive(pRecvMsg); assert(stat == OS_SUCCESS); delete pRecvMsg; assert(pMsgQ1->numMsgs() == 1); stat = pMsgQ1->receive(pRecvMsg); assert(stat == OS_SUCCESS); delete pRecvMsg; assert(pMsgQ1->numMsgs() == 0); delete pMsg1; delete pMsg2; #if !defined(_VXWORKS) try { OsMsgQ* pMsgQ2 = new OsMsgQ(OsMsgQ::DEF_MAX_MSGS, OsMsgQ::DEF_MAX_MSG_LEN, OsMsgQ::Q_PRIORITY, "MQ1"); delete pMsgQ2; } catch (const OsExcept* exc) { UtlString txt; cout << "Exception:" << endl; cout << " Major Code: " << exc->getMajorCode() << endl; cout << " Minor Code: " << exc->getMinorCode() << endl; txt = exc->getText(); cout << " Text: " << txt.data() << endl; txt = exc->getContext(); cout << " Context: " << txt.data() << endl; delete exc; } #endif delete pMsgQ1; /* ============================ OsCallback ================================ */ OsCallback* pCallback; pCallback = new OsCallback(12345, handleTimerEvent); pCallback->signal(67890); delete pCallback; /* ============================ OsEvent =================================== */ OsTime eventTimeout(2,0); OsEvent* pEvent; cout << "Testing OsEvent, please wait..." << endl; pEvent = new OsEvent(12345); int epochTime = time(NULL); assert(pEvent->wait(eventTimeout) != OS_SUCCESS); pEvent->signal(67890); assert(pEvent->wait(eventTimeout) == OS_SUCCESS); pEvent->reset(); assert(pEvent->wait(eventTimeout) != OS_SUCCESS); epochTime = time(NULL) - epochTime; // Make sure we waited (approximately) 2 seconds each time. assert(epochTime > 2 && epochTime < 6); delete pEvent; cout << "Done testing OsEvent." << endl; /* ============================ OsConfigDb ================================ */ OsConfigDb* pConfigDb; pConfigDb = new OsConfigDb(); delete pConfigDb; /* ============================ OsTimerTask =============================== */ OsTimerTask* pTimerTask; pTimerTask = OsTimerTask::getTimerTask(); OsTask::delay(500); // wait 1/2 second osPrintf("Going to delete the timer task.\n"); delete pTimerTask; /* ============================ OsTimer =================================== */ pTimerTask = OsTimerTask::getTimerTask(); OsTask::delay(500); // wait 1/2 second OsCallback* pNotifier; OsCallback* pNotifier2; OsTimer* pTimer; OsTimer* pTimer2; OsTime tenMsec(0, 10000);// timer offset ten msec into the future OsTime oneSecond(1,0); // timer offset one second into the future OsTime twoSeconds(2,0); // timer offset two seconds into the future OsTime tenSeconds(10,0); // timer offset ten seconds into the future OsTime tenYears(10*365*24*60*60, 0); // ten years into the future cout << "About to handle timer 1 (immediate)" << endl; pNotifier = new OsCallback(1, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer 1 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->oneshotAfter(OsTime::NO_WAIT); delete pTimer; delete pNotifier; cout << "About to handle timer 2" << endl; pNotifier = new OsCallback(2, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer 2 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->oneshotAfter(oneSecond); delete pTimer; // delete the timer before it can expire delete pNotifier; cout << "About to handle timer 3" << endl; pNotifier = new OsCallback(3, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer 3 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->oneshotAfter(oneSecond); pTimer->stop(); // stop the timer before it can expire delete pTimer; delete pNotifier; cout << "About to handle timer 4 (after 1 sec)" << endl; pNotifier = new OsCallback(4, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer armed at " << OsDateTime::getSecsSinceEpoch() << endl; pTimer->oneshotAfter(oneSecond); OsTask::delay(1500); // sleep for 1.5 seconds delete pTimer; delete pNotifier; cout << "About to handle timer 5" << endl; pNotifier = new OsCallback(5, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Periodic timer 5 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->periodicEvery(oneSecond, oneSecond); delete pTimer; // delete the timer before it can expire delete pNotifier; cout << "About to handle timer 6" << endl; pNotifier = new OsCallback(6, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Periodic timer 6 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->periodicEvery(oneSecond, oneSecond); pTimer->stop(); // stop the timer before it can expire delete pTimer; delete pNotifier; cout << "About to handle timer 7 (immediate, then every second)" << endl; cout << "About to handle timer 8 (immediate, then every two seconds)" << endl; pNotifier = new OsCallback(7, handleTimerEvent); pNotifier2 = new OsCallback(8, handleTimerEvent); pTimer = new OsTimer(*pNotifier); pTimer2 = new OsTimer(*pNotifier2); cout << " Periodic timer 7 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->periodicEvery(OsTime::NO_WAIT, oneSecond); cout << " Periodic timer 8 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer2->periodicEvery(OsTime::NO_WAIT, twoSeconds); OsTask::delay(4500); // sleep for 4.5 seconds pTimer->stop(); pTimer2->stop(); delete pTimer; delete pTimer2; delete pNotifier; delete pNotifier2; cout << "About to handle timer 9 (after ten seconds)" << endl; pNotifier = new OsCallback(9, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer 9 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->oneshotAfter(tenSeconds); OsTask::delay(12000); // sleep for 12 seconds delete pTimer; delete pNotifier; cout << "About to handle timer 10 (after 6912 seconds)" << endl; OsTime secs6912(6912, 0); pNotifier = new OsCallback(10, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer 10 armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->oneshotAfter(secs6912); OsTask::delay(12000); // sleep for 12 seconds delete pTimer; delete pNotifier; cout << "Verify that we can schedule timers in the distant future" << endl; pNotifier = new OsCallback(11, handleTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Oneshot timer armed 11 at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->oneshotAfter(tenYears); pTimer->stop(); pTimer->periodicEvery(OsTime::NO_WAIT, tenYears); pTimer->stop(); delete pTimer; delete pNotifier; cout << "Run 100x/second timer for 2 seconds..." << endl; int rapidTimerExpirations = 0; pNotifier = new OsCallback(&rapidTimerExpirations, handleRapidTimerEvent); pTimer = new OsTimer(*pNotifier); cout << " Rapid-fire timer armed at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; pTimer->periodicEvery(OsTime::NO_WAIT, tenMsec); OsTask::delay(2000); pTimer->stop(); cout << " Rapid-fire timer stopped at " << OsDateTime::getSecsSinceEpoch() << " secs" << endl; cout << "Rapid-fire timer expired " << rapidTimerExpirations << " times" << endl; delete pTimer; delete pNotifier; /* ============================ OsTimerTask cleanup ======================= */ // The timer task may have been created indirectly (as a result of // creating OsTimer objects). If the timer task exists, delete it now. pTimerTask = OsTimerTask::getTimerTask(); if (pTimerTask != NULL) { osPrintf("Going to delete the timer task.\n"); delete pTimerTask; } /* ============================ OsNameDb cleanup ========================== */ // The name database may have been created indirectly (as a result of // creating objects with global names). If the name database exists, // delete it now. pNameDb = OsNameDb::getNameDb(); if (pNameDb != NULL) delete pNameDb; /* ============================ Testing Finish ============================ */ cout << "Leaving main()" << endl; #ifdef TEST assert(pMemCheck->delta() == 0); // check for memory leak delete pMemCheck; #endif //TEST return 0; }
int main(int argc, char* argv[]) { parseArgs(argc, argv); initLogger(argv); OsEvent taskDone; Url url(xmlrpcURI); if (MemCheckDelay) { // Delay 45 seconds to allow memcheck start printf("Wating %d seconds for start of memcheck ...", MemCheckDelay); OsTask::delay(MemCheckDelay * 1000); printf("starting\n"); } // If an input file was specified we start up the number // of specified threads to execute that input file. If number // of threads wasn't specified we start up 1 thread. if (bInputFile) { int signaled = 0; for (int i=0; i<numThreads; i++) { ClientTask* pTask = new ClientTask(&taskDone); pTask->start(); } // Wait for threads to shut down while (signaled < numThreads) { taskDone.wait(); taskDone.reset(); ++signaled; } exit(0); } switch (Method) { case Version: // --version <xmlrpc URI> <dataset> { if (optind < argc) { fprintf(stderr, "Too many arguments: '%s'\n", argv[optind]); showHelp(argv); exit(1); } requestVersion(url); break; } case Get: // --get <xmlrpc URI> <dataset> <name> ... { UtlSList names; // copy remaining arguments into the names list while (optind < argc) { names.append(new UtlString(argv[optind++])); } requestGet(url, names); break; } case Set: // --set <xmlrpc URI> <dataset> <name> <value> [ <name> <value> ] ... { UtlHashMap parameters; // copy remaining arguments into the names list while (optind + 1 < argc) { UtlString* setName = new UtlString(argv[optind++]); UtlString* setValue = new UtlString(argv[optind++]); parameters.insertKeyAndValue(setName, setValue); } if (optind < argc) { fprintf(stderr, "name '%s' without a value\n", argv[optind]); showHelp(argv); exit(1); } if (parameters.isEmpty()) { fprintf(stderr, "must specify at least one name and value\n"); showHelp(argv); exit(1); } else { requestSet(url, parameters); parameters.destroyAll(); } break; } case Delete: // --delete <xmlrpc URI> <dataset> <name> ... { UtlSList names; // copy remaining arguments into the names list while (optind < argc) { names.append(new UtlString(argv[optind++])); } requestDelete(url, names); break; } default: fprintf(stderr, "No method specified\n"); showHelp(argv); exit(1); } if (MemCheckDelay) { // Delay 45 seconds to allow memcheck start printf("Wating %d seconds for stop of memcheck ...", MemCheckDelay); OsTask::delay(MemCheckDelay * 1000); printf("starting\n"); } exit(0); }