示例#1
0
SmartIF<IService> ServiceLocatorHelper::service(const std::string &name, const bool quiet, const bool createIf) const {
  SmartIF<IService> theSvc;
  if (isInThread()) {
    //first we look for  a thread-specific version of the service
    theSvc = serviceLocator()->service(name + threadName(), createIf);
  }
  // if not, try to find the common, single-threaded version of the service
  if (!theSvc.isValid()){
    theSvc = serviceLocator()->service(name, createIf);
  }

  if (theSvc.isValid()) {
    if (!quiet) {
      if (UNLIKELY(log().level() <= MSG::VERBOSE))
        log() << MSG::VERBOSE
              << "ServiceLocatorHelper::service: found service " << name <<endmsg;
    }
  } else {
    // if not return an error
    if (!quiet) {
      log() << MSG::ERROR
            << "ServiceLocatorHelper::service: can not locate service "
            << name;
      if (isInThread()) log() << MSG::ERROR << " or " << name + threadName();
      log() << MSG::ERROR << endmsg;
    }
  }
  return theSvc;
}
示例#2
0
TCPServer::TCPServer(TCPServerConnectionFactory::Ptr pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams::Ptr pParams):
	_socket(socket),
	_pDispatcher(new TCPServerDispatcher(pFactory, threadPool, pParams)),
	_thread(threadName(socket)),
	_stopped(true)
{
}
示例#3
0
TCPServer::TCPServer(TCPServerConnectionFactory::Ptr pFactory, Poco::UInt16 portNumber, TCPServerParams::Ptr pParams):
	_socket(ServerSocket(portNumber)),
	_pDispatcher(new TCPServerDispatcher(pFactory, Poco::ThreadPool::defaultPool(), pParams)),
	_thread(threadName(_socket)),
	_stopped(true)
{
}
示例#4
0
TCPServer::TCPServer(TCPServerConnectionFactory* pFactory, const ServerSocket& socket, TCPServerParams* pParams):
_socket(socket),
_pDispatcher(new TCPServerDispatcher(pFactory, Poco::ThreadPool::defaultPool(), pParams)),
_thread(threadName(socket)),
_stopped(true)
{
}
示例#5
0
文件: win32.cpp 项目: zeedh/fastiva
void os_changeThreadPriority(Thread* thread, int newPriority)
{
	FASTIVA_LATE_IMPL();
#if 0
	if (newPriority < 1 || newPriority > 10) {
        ALOGW("bad priority %d", newPriority);
        newPriority = 5;
    }

    int newNice = kNiceValues[newPriority-1];
    pid_t pid = thread->systemTid;

    if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
        set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
    } else if (getpriority(PRIO_PROCESS, pid) >= ANDROID_PRIORITY_BACKGROUND) {
        set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
    }

    if (setpriority(PRIO_PROCESS, pid, newNice) != 0) {
        std::string threadName(dvmGetThreadName(thread));
        ALOGI("setPriority(%d) '%s' to prio=%d(n=%d) failed: %s",
        pid, threadName.c_str(), newPriority, newNice, strerror(errno));
    } else {
        ALOGV("setPriority(%d) to prio=%d(n=%d)", pid, newPriority, newNice);
    }
#endif
}
// ----------------------------------------------------------------------------
// CSIPClientResolver::CreateWorkerThreadL
// ----------------------------------------------------------------------------
//   
void CSIPClientResolver::CreateWorkerThreadL()
    {
    TName threadName(KWorkerThreadName);
    // Append a random number to make the name unique
    const TInt KThreadIdWidth = 10;
    threadName.AppendNumFixedWidthUC(Math::Random(), EHex, KThreadIdWidth);
    RThread thread;
    TInt err = thread.Create(threadName,
                             WorkerThreadFunction,
                             KDefaultStackSize,
                             NULL, // Use the same heap as the main thread
                             this);
    User::LeaveIfError(err);
    TRequestStatus status;
    thread.Logon(status);
    thread.Resume();
    User::WaitForRequest(status);
    TExitType exitType = thread.ExitType();
    thread.Close();
    if (exitType == EExitPanic)
        {
        User::Leave(KErrGeneral);
        }
    User::LeaveIfError(status.Int());
    }
示例#7
0
void CIoLog::LogCompletion(const RMsg& aMessage, TInt aError)
	{
	TFullName threadName(_L("unknown"));
	TRAP_IGNORE(threadName = ClientNameL(aMessage));
	CIoLog& self = Self();
	self.iScratchBuf.SetLength(0);
	TOverflowTruncate overflow;
	self.iScratchBuf.AppendFormat(_L("Completing %S's request (opcode: %S, message handle: %d) with %S(%d)"), &overflow, &threadName, StringifyOpcode(aMessage.Function()), static_cast<const RMessageAccess&>(aMessage).Handle(), StringifyError(aError), aError);
	self.Write(self.iScratchBuf);
	}
示例#8
0
/**
* Creates a second thread to run the test.
* 
* @param aFunctionIndex The drawing function command to be executed. All commands are defined in TestFunctionIndex.
*/
void CTW32CmdBuf::CreateSecondThreadAndDoTestL(TTestFunctionIndex aFunctionIndex)
	{	
	RThread thread;
	TBuf<30> threadName(KTW32CmdBufSecondThread);
	static TInt threadSerialNumber = 0;
	threadName.AppendNum(++threadSerialNumber);
	User::LeaveIfError(thread.Create(threadName, TestCmdBufFunction, KDefaultStackSize, KMinHeapSize, 0x4000, &aFunctionIndex));
	TRequestStatus status;
	thread.Logon(status);
	thread.Resume();
	User::WaitForRequest(status);
	TEST(thread.ExitType()==EExitKill);
	TEST(thread.ExitReason() == KErrNone);
	thread.Close();	
	}
示例#9
0
void CCmdUndertaker::DoRunL()
	{	
	User::LeaveIfError(iUndertaker.Create());

	if (iParanoid)
		{
		User::LeaveIfError(iMainThread.Open(RThread().Id()));
		User::LeaveIfError(iLock.CreateLocal());
		iHandles.ReserveL(10);
		TFullName threadName(RThread().Name());
		threadName.Append(_L("_worker"));
		LeaveIfErr(iWorkerThread.Create(threadName, &WorkerThreadFn, 8192, NULL, this), _L("Couldn't create worker thread"));
#ifdef FSHELL_MEMORY_ACCESS_SUPPORT
		LoadMemoryAccessL();
		LeaveIfErr(iMemAccess.SetThreadPriority(iWorkerThread, 31), _L("Couldn't set worker thread priority with memoryaccess"));
#else
		iWorkerThread.SetPriority(EPriorityMuchMore); // Best we can do
#endif
		iWorkerThread.Resume();
		}
	else
		{
		User::LeaveIfError(Queue());
		}	
		
	if (Stdin().IsForeground() > 0)
		{
		Write(iAll ? _L("Waiting for any thread exit...\r\n") : _L("Waiting for panicked thread exit...\r\n"));
		}
		
	if (iParanoid)
		{
		// We've spawned off our worker thread, which is the client of the RUndertaker. We now wait for it to signal us back again.
		// It's easier to balance the requests if we don't go through the active scheduler (so long as nothing else signals this thread!)
		for (;;)
			{
			User::WaitForRequest(iMainThreadStat);
			if (iMainThreadStat.Int() != KErrNone) User::Leave(iMainThreadStat.Int());
			iLock.Wait();
			TInt handle = iHandles[0];
			iHandles.Remove(0);
			iLock.Signal();
			ProcessHandle(handle);
			}
		}
	}
示例#10
0
文件: Stack.cpp 项目: nesl/CAreDroid
static void printWaitMessage(const DebugOutputTarget* target, const char* detail, Object* obj,
        Thread* thread)
{
    std::string msg(StringPrintf("  - waiting %s <%p> ", detail, obj));

    if (obj->clazz != gDvm.classJavaLangClass) {
        // I(16573)   - waiting on <0xf5feda38> (a java.util.LinkedList)
        // I(16573)   - waiting on <0xf5ed54f8> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
        msg += "(a " + dvmHumanReadableType(obj) + ")";
    }

    if (thread != NULL) {
        std::string threadName(dvmGetThreadName(thread));
        StringAppendF(&msg, " held by tid=%d (%s)", thread->threadId, threadName.c_str());
    }

    dvmPrintDebugMessage(target, "%s\n", msg.c_str());
}
EXPORT_C TInt NewServer()
/**
 * @return - Standard Epoc error codes
 * Non-secure variant only
 * 1st and only ordinal, called by the client API to initialise the server
 */
	{
	_LIT(KThread,"Thread");
	RThread thread;
	TBuf<KMaxTestExecuteNameLength> threadName(KServerName);
	// Create a hopefully unique thread name and use the ThreadFunc
	threadName.Append(KThread);
	const TInt KMaxHeapSize = 0x1000000;			//< Allow a 1Mb max heap
	TInt err = thread.Create(threadName, ThreadFunc, KDefaultStackSize, KMinHeapSize, KMaxHeapSize, NULL, EOwnerProcess);
	if(err)
		return err;
	thread.Resume();
	thread.Close();
	return KErrNone;
	}
示例#12
0
/**
@SYMTestCaseID			SYSLIB-SQL-CT-1613
@SYMTestCaseDesc		Multiple connections to the same database from different threads. 
						Each thread inserts set of record to the same table. Verify that all expected records
						and their column values meet the expectations.
@SYMTestPriority		High
@SYMTestActions			Testing SQL engine behaviour when having mutiple connections to the same database
						from different threads.
@SYMTestExpectedResults Test must not fail
@SYMREQ					REQ5792
                        REQ5793
*/	
void TestMultiConnDiffThread()
	{
	//Create a test database
	RDebug::Print(_L("+++:MainThread: Create test database\r\n"));
	RSqlDatabase db;
	TInt err = db.Create(KTestDbName1);
	TEST2(err, KErrNone);
	
	//Create a test table
	RDebug::Print(_L("+++:MainThread: Create a table in the test database\r\n"));
	_LIT8(KCreateSql, "CREATE TABLE A(Id INTEGER PRIMARY KEY)");
	err = db.Exec(KCreateSql);
	TEST(err >= 0);
	
	const TInt KThreadCnt = 4;
	const TInt KRange = 100;
	
	const TInt KIsolationLevelCnt = 2;
	TPtrC KIsolationLevelName[KIsolationLevelCnt] = {_L("Read Uncommitted"), _L("Serializable")};
	const RSqlDatabase::TIsolationLevel KIsolationLevels[KIsolationLevelCnt] = {
											RSqlDatabase::EReadUncommitted, RSqlDatabase::ESerializable};
											
	const TInt KTransTypeCnt = 2;											

	//Do the tests:
	// - doing each per thread database operation in a single transaction;
	// - doing all per thread database operations in a single transaction;
	for(TInt transType=0;transType<KTransTypeCnt;++transType)	
		{
		//For both supported isolation levels: read uncommitted and serializable
		for(TInt isolLevel=0;isolLevel<KIsolationLevelCnt;++isolLevel)
			{
			TInt low = 1;
			TInt high = KRange;
			
			RDebug::Print(_L("+++:MainThread: Test: thread count %d, records %d, trans type %d, isolation level: %S\r\n"), 
									KThreadCnt, KRange, transType, &KIsolationLevelName[isolLevel]);
									
			RThread thread[KThreadCnt];
			TRequestStatus status[KThreadCnt];
			TThreadData	data[KThreadCnt];

			//Create the test threads and run them. Each thread establishes a connection with the test database
			//and attempts to write set of records in the test table.
			TInt j;
			for(j=0;j<KThreadCnt;++j,low=high+1,high+=KRange)
				{
				data[j].iTransType = transType;
				data[j].iIsolationLevel = KIsolationLevels[isolLevel];
				data[j].iLowRecNo = low;
				data[j].iHighRecNo = high;
				
				_LIT(KThreadName,"Thr-");
				TBuf<32> threadName(KThreadName);
				threadName.AppendNum((TInt64)j + 1);
				
				TEST2(thread[j].Create(threadName, &ThreadFunc, 0x2000, 0x1000, 0x10000, (void*)&data[j], EOwnerThread), KErrNone);
				thread[j].Logon(status[j]);
				TEST2(status[j].Int(), KRequestPending);
				thread[j].Resume();
				}
			
			User::After(2000000);
			//Wait until threads finish the database operations and close them.				
			for(j=0;j<KThreadCnt;++j)
				{
				User::WaitForRequest(status[j]);
				TEST(thread[j].ExitType() != EExitPanic);
				thread[j].Close();
				}

			//Check that all records which are esupposed to be in the database, are there.
			RDebug::Print(_L("+++:MainThread: Check that all records have been written\r\n"));
			_LIT8(KSelectSql1, "SELECT COUNT(*) FROM A;");
			RSqlStatement stmt;
			err = stmt.Prepare(db, KSelectSql1);
			TEST2(err, KErrNone);
			err = stmt.Next();
			TEST2(err, KSqlAtRow);
			TInt cnt = stmt.ColumnInt(0);
			TEST2(cnt, KThreadCnt * KRange);
			stmt.Close();
			
			//Check that all records have expected column values.
			RDebug::Print(_L("+++:MainThread: Check that all records have expected column values\r\n"));
			_LIT8(KSelectSql2, "SELECT * FROM A;");
			err = stmt.Prepare(db, KSelectSql2);
			TEST2(err, KErrNone);
			for(TInt k=0;k<(KThreadCnt*KRange);++k)
				{
				err = stmt.Next();
				TEST2(err, KSqlAtRow);
				TInt val = stmt.ColumnInt(0);
				TEST(val > 0 && val <= (KThreadCnt * KRange));
				}
			stmt.Close();

			//Prepare for the next test run - delete all records.
			RDebug::Print(_L("+++:MainThread: Delete all records\r\n"));
			_LIT8(KDeleteSql, "DELETE FROM A");
			err = db.Exec(KDeleteSql);
			TEST(err >= 0);
			}//end of "for(TInt isolLevel=0;isolLevel<KIsolationLevelCnt;++isolLevel)"
		}//end of "for(TInt transType=0;transType<KTransTypeCnt;++transType)"
		
	db.Close();
	RDebug::Print(_L("+++:MainThread: Delete the test database\r\n"));
	(void)RSqlDatabase::Delete(KTestDbName1);
	}
EXPORT_C void StartServerL(const TDesC& aServerName, TUid aServerUid3, const TDesC& aServerFileName)
#endif
{
	CALLSTACKITEM_N(_CL(""), _CL("StartServer"));

	TBuf<50> mutexname; MakeServerMutexName(mutexname, aServerName);
	RAMutex mutex; mutex.GlobalLA(mutexname);
	
	TFindServer findServer(aServerName);
	TFullName name;
	
	if (findServer.Next(name) == KErrNone)
        {
		return;
        }
	
#if defined(__WINS__)
	RAThread serverthread;
#else
	RAProcess serverthread;
#endif
	TBuf<50> semaphorename; MakeServerSemaphoreName(semaphorename, aServerName);
	RSemaphore semaphore;
	if (semaphore.CreateGlobal(semaphorename, 0)!=KErrNone) {
		User::LeaveIfError(semaphore.OpenGlobal(semaphorename));
	}

#if defined(__WINS__)
	CreateServerProcessLA(aServerName, aFunction, serverthread);
#else
	CreateServerProcessLA(aServerName, aServerUid3, aServerFileName, serverthread);
#endif
	
	TTimeIntervalMicroSeconds32 w(10*1000);
	TInt i=0;
	TInt result=KErrTimedOut;
	while (i < 17) { 
		// a couple of minutes, in case there's some db conversion or the like
#ifdef __S60V3__
		if (semaphore.Wait(w.Int())==KErrNone) {
#else
		if ( semaphore.Count()>0) {
#endif
			result=KErrNone;
			break;
		}
		TExitType etype=serverthread.ExitType();
		if (etype!=EExitPending) {
			// server died
			result=KErrServerTerminated;
			break;
		}
#ifndef __S60V3__
		User::After(w);
#endif
		w=w.Int()*2;
		i++;
	}
	if (result!=KErrNone) {
		User::Leave(result);
	}

	semaphore.Close();
}

#if defined(__WINS__)
void CreateServerProcessLA(const TDesC& aServerName, TThreadFunction aFunction,
				RAThread& aThreadInto)
#else
#  if defined(__WINS__)
void CreateServerProcessLA(const TDesC& aServerName, TUid aServerUid3, 
				    const TDesC& aServerFileName,
				RAThread& aThreadInto)
#  else
void CreateServerProcessLA(const TDesC& aServerName, TUid aServerUid3, 
				    const TDesC& aServerFileName,
				RAProcess& aThreadInto)
#  endif
#endif
{
	CALLSTACKITEM_N(_CL(""), _CL("CreateServerProcess"));

	TInt result;
	
	
#if defined(__WINS__)
	
//#  if !defined(EKA2)
#if 0
	const TUidType serverUid(KNullUid, KNullUid, aServerUid3);
	RLibrary lib;
	TInt err=lib.Load(aServerFileName, _L("z:\\system\\programs"), serverUid);
	if (err!=KErrNone) {
		err=lib.Load(aServerFileName);
	}
	User::LeaveIfError(err);
	
	//  Get the WinsMain function
	TLibraryFunction functionWinsMain = lib.Lookup(1);
	
	//  Call it and cast the result to a thread function
	TThreadFunction serverThreadFunction = reinterpret_cast<TThreadFunction>(functionWinsMain());
#  else
	TThreadFunction serverThreadFunction = aFunction;
#  endif
	
	TName threadName(aServerName);
	
	// Append a random number to make it unique
	threadName.AppendNum(Math::Random(), EHex);
	
#  if 0
//#  if !defined(EKA2)
	aThreadInto.CreateLA(threadName,   // create new server thread
		serverThreadFunction, // thread's main function
		KDefaultStackSize,
		NULL,  // parameters
		&lib,
		NULL,
		KServerMinHeapSize,
		KServerMaxHeapSize,
		EOwnerProcess);
	lib.Close();    // if successful, server thread has handle to library now
	
#  else
	aThreadInto.CreateLA(threadName, serverThreadFunction, 
		KDefaultStackSize,
		KServerMinHeapSize, KServerMaxHeapSize, 0, EOwnerProcess);

#  endif
	
	aThreadInto.SetPriority(EPriorityMore);
	
#else
	
	const TUidType serverUid(KNullUid, KNullUid, aServerUid3);
	aThreadInto.CreateLA(aServerFileName, _L(""), serverUid);
	
#endif
	
	aThreadInto.Resume();
	
}
TInt CTe_locsrvSuiteStepBase::DoPanicTestL(TThreadFunction aThreadFunction, TExitCategoryName aExpectedExitCat,
                  TInt aExpectedExitReason, TTimeIntervalMicroSeconds32 aTimeoutValue)

{
#ifdef __WINS__
    User::SetJustInTime(EFalse);
    CleanupStack::PushL(TCleanupItem(TurnJITBackOn));
#endif
    RThread panickingThread;

    SPanicThreadFunctionData threadData;
    threadData.iPanicFunction = aThreadFunction;
    threadData.iPtr = NULL;

    // check that thread does not already exist
    TInt result = KErrNone;
    TBuf<24> threadName(KPanicThreadName);
    
    result = panickingThread.Create(
                threadName,
                PanicThreadFunction,
                KDefaultStackSize,
                KTestHeapMinSize,
                KTestHeapMaxSize,
                &threadData,
                EOwnerProcess);

    CheckExpectedResult(result, KErrNone, KUnexpectedErrorCreatingPanicThread);
    User::LeaveIfError(result);

    CleanupClosePushL(panickingThread);

    RTimer timeoutTimer;
    User::LeaveIfError(timeoutTimer.CreateLocal());
    CleanupClosePushL(timeoutTimer);

    TRequestStatus timerStatus;
    timeoutTimer.After(timerStatus, aTimeoutValue);

    TRequestStatus threadStatus;

    panickingThread.Rendezvous(threadStatus);
    if (threadStatus != KRequestPending)
        {
        // logon failed - thread is not yet running, so cannot have terminated
        User::WaitForRequest(threadStatus);              // eat signal
        panickingThread.Kill(threadStatus.Int());        // abort startup
        }
    else
        {
        panickingThread.Resume();
        User::WaitForRequest(threadStatus, timerStatus);
        }

    TInt exitReason = KErrNone;
    if (threadStatus == KRequestPending)
    {
        ERR_PRINTF1(KThreadDidntDieKillIt);
        panickingThread.Kill(KErrTimedOut);
        User::WaitForRequest(threadStatus);
    }
    else // (timerStatus == KRequestPending)
    {
        // stop timer
        timeoutTimer.Cancel();
        User::WaitForRequest(timerStatus);
    }

    exitReason = panickingThread.ExitReason();
    TExitCategoryName exitCat = panickingThread.ExitCategory();
    
    switch(panickingThread.ExitType()) 
    {
        case EExitKill:
            INFO_PRINTF2(KThreadWasKilled, exitReason);
            break;
        case EExitTerminate:
            INFO_PRINTF2(KThreadWasTerminated, exitReason);
            break;
        case EExitPanic:
            // check exit reasons
            if (exitCat.Compare(aExpectedExitCat) != 0)
                {
                INFO_PRINTF3(KUnexpectedPanicCategory, &exitCat, &aExpectedExitCat);
                }
            CheckExpectedResult(exitReason, aExpectedExitReason, KUnexpectedPanicReason);
            break;
        default:
            CheckExpectedResult((TInt)EExitPanic, threadStatus.Int(), KUnexpectedThreadExitType);
            break;
    }

    CleanupStack::PopAndDestroy(&timeoutTimer);
    CleanupStack::PopAndDestroy(&panickingThread);
#ifdef __WINS__
    CleanupStack::PopAndDestroy();  //TurnJITBackOn
#endif
    // wait a bit to make sure this thread is over
    const TTimeIntervalMicroSeconds32 KThreadDelay = 1000 * 1000; // 1 s
    User::After(KThreadDelay);

    return exitReason;
}
示例#15
0
std::string
ServiceLocatorHelper::threadedName(const std::string& name) const {
  return ( isInThread() ? name + threadName() : name );
}
/*
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
*/
static TInt CreateLockServerProcess()
    {
    TInt result;

	const TUidType serverUid(KNullUid, KNullUid, KCrashServerUid3);

#ifdef __WINS__

	RLibrary lib;
	result = lib.Load(KCrashServerImg, serverUid);
    if (result != KErrNone)
        {
        return  result;
        }

    //  Get the WinsMain function
	TLibraryFunction functionWinsMain = lib.Lookup(1);

    //  Call it and cast the result to a thread function
	TThreadFunction serverThreadFunction = reinterpret_cast<TThreadFunction>(functionWinsMain());

	TName threadName(KCrashServerName);

	// Append a random number to make it unique
	threadName.AppendNum(Math::Random(), EHex);

	RThread server;

	result = server.Create(threadName,   // create new server thread
							 serverThreadFunction, // thread's main function
							 KDefaultStackSize,
							 NULL,
							 &lib,
							 NULL,
							 KServerMinHeapSize,
							 KServerMaxHeapSize,
							 EOwnerProcess);

	lib.Close();	// if successful, server thread has handle to library now

    if (result != KErrNone)
        {
        return  result;
        }

	server.SetPriority(EPriorityMore);


#else

	RProcess server;

	result = server.Create(KCrashServerImg, _L(""), serverUid);
    if (result != KErrNone)
        {
        return  result;
        }

#endif

	server.Resume();
    server.Close();

    return  KErrNone;
    }
示例#17
0
文件: Log.cpp 项目: nob13/jxvm
std::ostream & logStreamPreformat (const char * file, int line, LogLevel level) {
    return logStream (level) << "[" << logLevelToString (level) << "]" << threadName() << " " << countLogLevel(level) <<  " " << myBaseName(file) << ":" << line <<  " ";
}