void CSpaceMultiThreadBalanceLength::Init(TConfigurationNode& t_tree) {
    /* Initialize the space */
    CSpace::Init(t_tree);
    /* Initialize thread related structures */
    int nErrors;
    /* Init mutexes */
    if((nErrors = pthread_mutex_init(&m_tStartSenseControlPhaseMutex, NULL)) ||
       (nErrors = pthread_mutex_init(&m_tStartActPhaseMutex, NULL)) ||
       (nErrors = pthread_mutex_init(&m_tStartPhysicsPhaseMutex, NULL)) ||
       (nErrors = pthread_mutex_init(&m_tStartMediaPhaseMutex, NULL)) ||
       (nErrors = pthread_mutex_init(&m_tFetchTaskMutex, NULL))) {
       THROW_ARGOSEXCEPTION("Error creating thread mutexes " << ::strerror(nErrors));
    }
    /* Init conditionals */
    if((nErrors = pthread_cond_init(&m_tStartSenseControlPhaseCond, NULL)) ||
       (nErrors = pthread_cond_init(&m_tStartActPhaseCond, NULL)) ||
       (nErrors = pthread_cond_init(&m_tStartPhysicsPhaseCond, NULL)) ||
       (nErrors = pthread_cond_init(&m_tStartMediaPhaseCond, NULL)) ||
       (nErrors = pthread_cond_init(&m_tFetchTaskCond, NULL))) {
       THROW_ARGOSEXCEPTION("Error creating thread conditionals " << ::strerror(nErrors));
    }
    /* Reset the idle thread count */
    m_unSenseControlPhaseIdleCounter = CSimulator::GetInstance().GetNumThreads();
    m_unActPhaseIdleCounter = CSimulator::GetInstance().GetNumThreads();
    m_unPhysicsPhaseIdleCounter = CSimulator::GetInstance().GetNumThreads();
    m_unMediaPhaseIdleCounter = CSimulator::GetInstance().GetNumThreads();
    /* Start threads */
    StartThreads();
 }
Exemple #2
0
void Network::InitializeClient(const char* ipAdress, const short port, const unsigned int maxDownstream, const unsigned int maxUpstream)
{
	std::cout << "Initializing client at port " << port << ".\n";

	_host = enet_host_create (NULL, 1, 2, maxDownstream, maxUpstream);

	if (_host == NULL)
		std::cout << "An error occurred while trying to create an ENet client host.\n";
	else
		std::cout << "Succesfully created ENet client host.\n";

	enet_address_set_host(&_address, ipAdress);
	_address.port = port;

	_peer = enet_host_connect(_host, &_address, 2, 0);

	if (_peer == NULL)
		std::cout << "No available peers for initiating an ENet connection.\n";

	// If connect send packages
	if (enet_host_service(_host, &_event, 1500) > 0 && _event.type == ENET_EVENT_TYPE_CONNECT)
	{
		_isConnected = true;
		printf("Connection to %s:%i succeeded.\n", ipAdress, _address.port);
		StartThreads();	
	}
	else
	{
		enet_peer_reset(_peer);
		printf("Connection to %s:%i failed.\n", ipAdress, _address.port);

	}
}
Exemple #3
0
void USBHost::UpdateWantDeterminism(const bool new_want_determinism)
{
  if (new_want_determinism)
    StopThreads();
  else if (IsOpened())
    StartThreads();
}
Exemple #4
0
 void ToastEngine::CreateFunctionalThreads()
 {
     m_OtherThreadPool.push_back(new (std::nothrow)FrontCommandProcessorThread());
     m_OtherThreadPool.push_back(new (std::nothrow)TimerThread());
     m_OtherThreadPool.push_back(new (std::nothrow)CommThread());
     StartThreads(m_OtherThreadPool);
     Log::Notice("Start other threads in Other Thread Pools");
 }
Exemple #5
0
ReturnCode USBHost::Open(const OpenRequest& request)
{
  // Force a device scan to complete, because some games (including Your Shape) only care
  // about the initial device list (in the first GETDEVICECHANGE reply).
  while (!UpdateDevices())
  {
  }
  StartThreads();
  return IPC_SUCCESS;
}
Exemple #6
0
int main (int argc, char *argv[])
{
	Option.iterations = 2;
	Option.loops = 4;
	Option.file_size = (1<<24);
	Option.numthreads = 1;
	punyopt(argc, argv, myopt, "bmnu");
	StartThreads();
	return 0;
}
  // Used by the WaitFor and WaitUntil tests to test that, without a predicate,
  // the timeout works properly.
  void WaitTimeTest(bool wait_for) {
    std::atomic<bool> timed_out{true};
    auto wait_until = [this, &timed_out, wait_for](std::atomic<bool> &done) {
      priority_lock lock(m_mutex);
      done = false;
      if (wait_for) {
        auto wait_time = std::chrono::milliseconds(100);
        timed_out =
            m_cond.wait_for(lock, wait_time) == std::cv_status::timeout;
      } else {
        auto wait_time =
            std::chrono::system_clock::now() + std::chrono::milliseconds(100);
        timed_out =
            m_cond.wait_until(lock, wait_time) == std::cv_status::timeout;
      }
      EXPECT_TRUE(lock.owns_lock())
          << "The condition variable should have reacquired the lock.";
      done = true;
    };

    // First, test without timing out.
    timed_out = true;
    StartThreads(wait_until);

    NotifyAllTest();
    EXPECT_FALSE(timed_out) << "The watcher should not have timed out.";

    TearDown();

    // Next, test and time out.
    timed_out = false;
    StartThreads(wait_until);

    ShortSleep(110);

    EXPECT_TRUE(m_done1) << "watcher1 should have timed out.";
    EXPECT_TRUE(m_done2) << "watcher2 should have timed out.";
    EXPECT_TRUE(timed_out) << "The watcher should have timed out.";
  }
TEST_F(ConditionVariableTest, NotifyAll) {
  auto wait = [this](std::atomic<bool> &done) {
    priority_lock lock(m_mutex);
    done = false;
    m_cond.wait(lock);
    EXPECT_TRUE(lock.owns_lock())
        << "The condition variable should have reacquired the lock.";
    done = true;
  };

  StartThreads(wait);

  NotifyAllTest();
}
TEST_F(ConditionVariableTest, WaitWithPredicate) {
  auto predicate = [this]() -> bool { return m_pred_var; };
  auto wait_predicate = [this, predicate](std::atomic<bool> &done) {
    priority_lock lock(m_mutex);
    done = false;
    m_cond.wait(lock, predicate);
    EXPECT_TRUE(lock.owns_lock())
        << "The condition variable should have reacquired the lock.";
    done = true;
  };

  StartThreads(wait_predicate);

  PredicateTest();
}
TEST_F(ConditionVariableTest, NativeHandle) {
  auto wait = [this](std::atomic<bool> &done) {
    priority_lock lock(m_mutex);
    done = false;
    m_cond.wait(lock);
    EXPECT_TRUE(lock.owns_lock())
        << "The condition variable should have reacquired the lock.";
    done = true;
  };

  StartThreads(wait);

  pthread_cond_t* native_handle = m_cond.native_handle();
  pthread_cond_broadcast(native_handle);
  ShortSleep();
  EXPECT_TRUE(m_done1) << "watcher1 failed to be notified.";
  EXPECT_TRUE(m_done2) << "watcher2 failed to be notified.";
}
TEST_F(ConditionVariableTest, NotifyOne) {
  auto wait = [this](std::atomic<bool> &done) {
    priority_lock lock(m_mutex);
    done = false;
    m_cond.wait(lock);
    EXPECT_TRUE(lock.owns_lock())
        << "The condition variable should have reacquired the lock.";
    done = true;
  };

  StartThreads(wait);

  NotifyOne();
  // Wait briefly to let things settle.
  ShortSleep();
  EXPECT_TRUE(m_done1 ^ m_done2) << "Only one thread should've been notified.";
  NotifyOne();
  ShortSleep();
  EXPECT_TRUE(m_done2 && m_done2) << "Both threads should've been notified.";
}
Exemple #12
0
void Network::InitializeServer(size_t maxPlayers)
{
	_address.host = ENET_HOST_ANY;
	_address.port = 1234;
	
	_host = enet_host_create(&_address, maxPlayers, 2, 0, 0);
	std::cout << "Initializing server at port " << _address.port << ".\n";
	if (_host == NULL)
	{
		std::cout << "An error occurred while trying to create an ENet server host.\n";
		StopThreads();
	}
	else
	{
		std::cout << "Succesfully creatinga ENet server host; server now running.\n";
		_isServer = true;
		_isConnected = true;
		StartThreads();
		
	}	
}
Exemple #13
0
ASSERTNAME

#include "PrintQueue.h"
#include "StandaloneDocument.h"

// ****************************************************************************
//
//  Function Name:	RPrintQueue::RPrintQueue
//
//  Description:		Constructor
//
//  Returns:			Nothing
//
//  Exceptions:		None
//
// ****************************************************************************
//
RPrintQueue::RPrintQueue( int nPrintThreads ) : RQueue<RStandaloneDocument>( )
	{
	StartThreads( nPrintThreads );
	}
void TestUserData(RPageMove& pagemove, TUint8* array, TInt size, TBool aPagedData=EFalse)
	{
	_T_PRINTF(_L("Fill the array with some data\n"));
	for (TInt i=0; i<size; i++) array[i] = i*i;

	TUint8* firstpage = (TUint8*)_ALIGN_DOWN((TLinAddr)array, PageSize);
	RThread thread;
	thread.Open(RThread().Id());
	SPinThreadArgs threadArgs;
	threadArgs.iLinAddr = (TLinAddr)array;
	threadArgs.iParentThread = thread;
	threadArgs.iRealtimeState = User::ERealtimeStateOff;

	TMovingPinStage endStage = EMovingPinStages;
	if (!gPinningSupported)
		endStage = EVirtualPinning;

	for (TUint state = ENoPinning; state < (TUint)endStage; state++)
		{
		TThreadFunction threadFunc = NULL;
		switch (state)
			{
			case ENoPinning:
				test.Printf(_L("Attempt to move pages while they are being modified\n"));
				threadFunc = &ReadWriteByte;
				break;
			case EVirtualPinning:
				test.Printf(_L("Attempt to move pages while they are being virtually pinned\n"));
				threadFunc = &VirtualPinPage;
				break;
			case EPhysicalPinning:
				test.Printf(_L("Attempt to move pages while they are being physically pinned\n"));
				threadFunc = &PhysicalPinPage;
				break;
			}
		ThreadDie = EFalse;
		TUint numThreads = (NumberOfCpus > 1) ? NumberOfCpus - 1 : 1;
		RThread* userDataThread = new RThread[numThreads];
		TRequestStatus* s = new TRequestStatus[numThreads];
		StartThreads(numThreads, userDataThread, s, threadFunc, threadArgs);

		_T_PRINTF(_L("Move first array page repeatedly\n"));
		TBool success=EFalse;
		TUint inuse = 0;
		*(volatile TUint8*)array = *array;	// Ensure the page of the first entry is paged in for the first move.
		for (TInt i=0; i < Repitions*2; i++)
			{
			TInt r = pagemove.TryMovingUserPage(firstpage, ETrue);
			if (i == 0)
				{// If this is the first run allow the pinning threads to 
				// unpin the memory now that we've definitely done at least 
				// one page move with the page pinned.
				_T_PRINTF(_L("signal to child\n"));
				RThread::Rendezvous(KErrNone);
				}
			switch (r)
				{
				case KErrInUse:
					inuse++;
					break;
				case KErrArgument:
					// The page was paged out, this should only happen for paged data.
					test(aPagedData);
					break;
				default:
					test_KErrNone(r);
					success=ETrue;
					break;
				}
			}
		// Can't guarantee that for paged data the page and its page tables will
		// be paged in, in most cases it will be at least once.
		// Pinning the page should always return KErrInUse except for virtually 
		// pinned non-paged memory as virtual pinning is a nop for unpaged memory.
		test.Printf(_L("inuse test removed; inuse %d\n"),inuse);
		//test(inuse || aPagedData || state == EVirtualPinning);
		test(success || state == EPhysicalPinning);

		ThreadDie = ETrue;
		EndThreads(numThreads, userDataThread, s);

		_T_PRINTF(_L("Validate page data\n"));
		for (TInt i=0; i<size; i++)
			test_Equal((TUint8)(i*i), array[i]);
		}
	thread.Close();
	}
void DrawerCommandQueue::Finish()
{
	auto queue = Instance();
	if (queue->commands.empty())
		return;

	// Give worker threads something to do:

	std::unique_lock<std::mutex> start_lock(queue->start_mutex);
	queue->active_commands.swap(queue->commands);
	queue->run_id++;
	start_lock.unlock();

	queue->StartThreads();
	queue->start_condition.notify_all();

	// Do one thread ourselves:

	DrawerThread thread;
	thread.core = 0;
	thread.num_cores = (int)(queue->threads.size() + 1);

	struct TryCatchData
	{
		DrawerCommandQueue *queue;
		DrawerThread *thread;
		size_t command_index;
	} data;

	data.queue = queue;
	data.thread = &thread;
	data.command_index = 0;
	VectoredTryCatch(&data,
	[](void *data)
	{
		TryCatchData *d = (TryCatchData*)data;

		for (int pass = 0; pass < d->queue->num_passes; pass++)
		{
			d->thread->pass_start_y = pass * d->queue->rows_in_pass;
			d->thread->pass_end_y = (pass + 1) * d->queue->rows_in_pass;
			if (pass + 1 == d->queue->num_passes)
				d->thread->pass_end_y = MAX(d->thread->pass_end_y, MAXHEIGHT);

			size_t size = d->queue->active_commands.size();
			for (d->command_index = 0; d->command_index < size; d->command_index++)
			{
				auto &command = d->queue->active_commands[d->command_index];
				command->Execute(d->thread);
			}
		}
	},
	[](void *data, const char *reason, bool fatal)
	{
		TryCatchData *d = (TryCatchData*)data;
		ReportDrawerError(d->queue->active_commands[d->command_index], true, reason, fatal);
	});

	// Wait for everyone to finish:

	std::unique_lock<std::mutex> end_lock(queue->end_mutex);
	queue->end_condition.wait(end_lock, [&]() { return queue->finished_threads == queue->threads.size(); });

	if (!queue->thread_error.IsEmpty())
	{
		static bool first = true;
		if (queue->thread_error_fatal)
			I_FatalError("%s", queue->thread_error.GetChars());
		else if (first)
			Printf("%s\n", queue->thread_error.GetChars());
		first = false;
	}

	// Clean up batch:

	for (auto &command : queue->active_commands)
		command->~DrawerCommand();
	queue->active_commands.clear();
	queue->memorypool_pos = 0;
	queue->finished_threads = 0;
}
  // For use with tests that have a timeout and a predicate.
  void WaitTimePredicateTest(bool wait_for) {
    // The condition_variable return value from the wait_for or wait_until
    // function should in the case of having a predicate, by a boolean. If the
    // predicate is true, then the return value will always be true. If the
    // condition times out and, at the time of the timeout, the predicate is
    // false, the return value will be false.
    std::atomic<bool> retval{true};
    auto predicate = [this]() -> bool { return m_pred_var; };
    auto wait_until =
        [this, &retval, predicate, wait_for](std::atomic<bool> &done) {
      priority_lock lock(m_mutex);
      done = false;
      if (wait_for) {
        auto wait_time = std::chrono::milliseconds(100);
        retval = m_cond.wait_for(lock, wait_time, predicate);
      } else {
        auto wait_time =
            std::chrono::system_clock::now() + std::chrono::milliseconds(100);
        retval = m_cond.wait_until(lock, wait_time, predicate);
      }
      EXPECT_TRUE(lock.owns_lock())
          << "The condition variable should have reacquired the lock.";
      done = true;
    };

    // Test without timing out and with the predicate set to true.
    retval = true;
    m_pred_var = true;
    StartThreads(wait_until);

    NotifyAllTest();
    EXPECT_TRUE(retval) << "The watcher should not have timed out.";

    TearDown();

    // Test with timing out and with the predicate set to true.
    retval = false;
    m_pred_var = false;
    StartThreads(wait_until);

    ShortSleep(110);

    EXPECT_TRUE(m_done1) << "watcher1 should have finished.";
    EXPECT_TRUE(m_done2) << "watcher2 should have finished.";
    EXPECT_FALSE(retval) << "The watcher should have timed out.";

    TearDown();

    // Test without timing out and run the PredicateTest().
    retval = false;
    StartThreads(wait_until);

    PredicateTest();
    EXPECT_TRUE(retval) << "The return value should have been true.";

    TearDown();

    // Test with timing out and the predicate set to true while we are waiting
    // for the condition variable to time out.
    retval = true;
    StartThreads(wait_until);
    ShortSleep();
    m_pred_var = true;
    ShortSleep(110);
    EXPECT_TRUE(retval) << "The return value should have been true.";
  }
Exemple #17
0
bool CMOOSSerialPort::Configure(STRING_LIST sParams)
{
    MOOSTrace("CMOOSSerialPort::Configure() : ");
    
    STRING_LIST::iterator p;
    
    for(p=sParams.begin();p!=sParams.end();++p)
    {
        std::string sLine = *p;
        
        std::string sTok = MOOSChomp(sLine,"=");
        
        std::string sVal = sLine;
        
        
        if(MOOSStrCmp(sTok,"PORT"))
        {
            m_sPort = sVal;
            MOOSTrace("%s,",m_sPort.c_str());
        }
        else if(MOOSStrCmp(sTok,"BAUDRATE"))
        {
            m_nBaudRate = atoi(sVal.c_str());
            
            if(m_nBaudRate==0)
            {
                m_nBaudRate = DEFAULT_BAUDRATE;
            }
            MOOSTrace("%d,",m_nBaudRate);
            
        }
        else if(MOOSStrCmp(sTok,"HANDSHAKING"))
        {
            if(MOOSStrCmp(sVal,"TRUE"))
            {
                m_bHandShaking = true;
            }
            else
            {
                m_bHandShaking = false;
            }
        }
        else if(MOOSStrCmp(sTok,"VERBOSE"))
        {
            
            if(MOOSStrCmp(sVal,"TRUE"))
            {
                m_bVerbose = true;
            }
            else
            {
                m_bVerbose = false;
            }
        }
        else if(MOOSStrCmp(sTok,"STREAMING"))
        {
            
            if(MOOSStrCmp(sVal,"TRUE"))
            {
                m_bStreaming = true;
            }
            else
            {
                m_bStreaming = false;
            }
            MOOSTrace("%s,",m_bStreaming?"streaming":"standard");
            
        }

        // ARH 14/05/2005 Added to allow use of the 500kbaud CSM PCMCIA card
        else if (MOOSStrCmp(sTok, "USECSMEXT"))
        {
            if (MOOSStrCmp(sVal, "TRUE"))
            {
                m_bUseCsmExt = true;
            }
            else
            {
                m_bUseCsmExt = false;
            }
        }
    }
    
    
    bool bSuccess = Create(m_sPort.c_str(),m_nBaudRate);
    
    if(bSuccess)
    {
        Flush();
        if(m_bStreaming)
        {
            bSuccess = StartThreads();
        }
    }
    
    MOOSTrace("%s\n",bSuccess?"OK":"FAILED");
    
    return bSuccess;
    
    
    
}
Exemple #18
0
int __cdecl main(int argc, char **argv) {

  // Initialize the global parameters
  params = &Globals;
  try_parse_args(params, argc, argv);


#ifdef SORA_PLATFORM
  // Start Sora HW
  if (Globals.inType == TY_SDR || Globals.outType == TY_SDR)
  {
#ifdef BLADE_RF
	  if (BladeRF_RadioStart(params) < 0)
	  {
		  exit(1);
	  }
#endif

#ifdef SORA_RF
	  // SORA
	  RadioStart(&Globals);
	  if (Globals.inType == TY_SDR)
	  {
		  InitSoraRx(params);
	  }
	  if (Globals.outType == TY_SDR)
	  {
		  InitSoraTx(params);
	  }
#endif
  }


  // Start NDIS
  if (Globals.inType == TY_IP || Globals.outType == TY_IP)
  {
	HRESULT hResult = SoraUEnableGetTxPacket();
	assert(hResult == S_OK);
	Ndis_init(NULL);
  }

  // Start measuring time
  initMeasurementInfo(&(Globals.measurementInfo), Globals.latencyCDFSize);
#endif


  // Init
  initBufCtxBlock(&buf_ctx);
  initHeapCtxBlock(&heap_ctx, Globals.heapSize);

  wpl_global_init(Globals.heapSize);
  wpl_input_initialize();


#ifdef SORA_PLATFORM
  /////////////////////////////////////////////////////////////////////////////  
  // DV: Pass the User_Routines here

  int no_threads = wpl_set_up_threads(User_Routines);

  printf("Setting up threads...\n");

  ULONGLONG ttstart, ttend;

  printf("Starting %d threads...\n", no_threads);
  StartThreads(&ttstart, &ttend, &Globals.measurementInfo.tsinfo, no_threads, User_Routines);

  printf("Total input items (including EOF): %d (%d B), output items: %d (%d B)\n",
	  buf_ctx.total_in, buf_ctx.total_in*buf_ctx.size_in,
	  buf_ctx.total_out, buf_ctx.total_out*buf_ctx.size_out);
  printf("Time Elapsed: %ld us \n",
	  SoraTimeElapsed((ttend / 1000 - ttstart / 1000), &Globals.measurementInfo.tsinfo));

  if (Globals.latencySampling > 0)
  {
	  printf("Min write latency: %ld, max write latency: %ld\n", (ulong)Globals.measurementInfo.minDiff, 
																 (ulong) Globals.measurementInfo.maxDiff);
	  printf("CDF: \n   ");
	  unsigned int i = 0;
	  while (i < Globals.measurementInfo.aDiffPtr)
	  {
		  printf("%ld ", Globals.measurementInfo.aDiff[i]);
		  if (i % 10 == 9)
		  {
			  printf("\n   ");
		  }
		  i++;
	  }
	  printf("\n");
  }


  // Free thread separators
  // NB: these are typically allocated in blink_set_up_threads
  ts_free();

#else
  int usec;
#ifdef __GNUC__
  struct timespec start, end;
  clock_gettime(CLOCK_MONOTONIC, &start);
  wpl_go();
  clock_gettime(CLOCK_MONOTONIC, &end);
  usec = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
#else
  clock_t start = clock(), diff;
  wpl_go();
  diff = clock() - start;
  usec = diff * 1000000 / CLOCKS_PER_SEC;
#endif
  printf("Time Elapsed: %d\n", usec);
#endif

  printf("Bytes copied: %ld\n", bytes_copied);

  wpl_output_finalize();

#ifdef SORA_PLATFORM
	// Stop Sora HW
	if (Globals.inType == TY_SDR || Globals.outType == TY_SDR)
	{
#ifdef BLADE_RF
		BladeRF_RadioStop(params);
#endif
#ifdef SORA_RF
		RadioStop(&Globals);
#endif
	}

	// Stop NDIS
	if (Globals.inType == TY_IP || Globals.outType == TY_IP)
	{
		if (hUplinkThread != NULL)
		{
			// Sora cleanup.
			SoraUThreadStop(hUplinkThread);
			SoraUThreadFree(hUplinkThread);
		}
		SoraUDisableGetTxPacket();
		// Winsock cleanup.
		closesocket(ConnectSocket);
		WSACleanup();
	}

#endif

  return 0;
}
// ---------------------------------------------------------
// CPosTp208::StartL
//
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CT_LbsClientPosTp208::StartL()
    {
    //first do a simple connection test
    TInt fasterr = DoFastConnectionL();
    _LIT(KFailConnect, "Fast connection failed");
    AssertTrueL(fasterr == KErrNone, KFailConnect, fasterr);  

    SetupPsyL(iUidMultiPsy);

    TInt nrOfRounds = 1;
    TBuf<100> buf;
    
    _LIT(KPsitionUpdate, 
    		">>>>>>>>>>Running StartThreads(ETrue) requesting position updates<<<<<<<<");
    INFO_PRINTF1(KPsitionUpdate);

    _LIT(KEmptySpace, "");
    _LIT(KRound, ">>>>>>Round nr %d :");
    _LIT(KErrorsFound, "Errors found!!!");
    
    for (TInt i=0; i<nrOfRounds; i++)
        {
        INFO_PRINTF1(KEmptySpace);
        buf.Format(KRound, i);
        INFO_PRINTF1(buf);
        TTime now, startTime;
        TTimeIntervalMicroSeconds requestTime;
        
        startTime.UniversalTime();
        TInt res = StartThreads(ETrue);
        if (res != KErrNone) 
        	LogErrorAndLeaveL(KErrorsFound, res);
        now.UniversalTime();
        
        requestTime = now.MicroSecondsFrom(startTime);
        _LIT(KDebug, "%d requests from %d threads took: %d microsecs.");
        buf.Zero();
        TInt64 reqTime = requestTime.Int64();
        buf.Format(KDebug, KNrOfClients * KNrOfRuns, KNrOfClients, reqTime);
        INFO_PRINTF1(buf);
      
        }

    _LIT(KConnectDisconnect, 
    		">>>>>>>>>>Running StartThreads(EFalse) connect/disconnect Epos<<<<<<<<");
    INFO_PRINTF1(KConnectDisconnect);
    nrOfRounds = 5;
    for (TInt j=0; j<nrOfRounds; j++)
        {
        INFO_PRINTF1(KEmptySpace);
        buf.Format(KRound, j);
        INFO_PRINTF1(buf);
        TTime now, startTime;
        TTimeIntervalMicroSeconds requestTime;
       
        startTime.UniversalTime();

        // Threads only connects to Epos server and then disconnect
        TInt res = StartThreads(EFalse);
        if (res != KErrNone) 
        	LogErrorAndLeaveL(KErrorsFound, res);
        now.UniversalTime();
        
        requestTime = now.MicroSecondsFrom(startTime);
        _LIT(KDebug, "%d threads connecting and disconnecting to Epos server took: %d microsecs.");
        buf.Zero();
        TInt64 reqTime = requestTime.Int64();
        buf.Format(KDebug, KNrOfClients, reqTime);
        INFO_PRINTF1(buf);
        }
    }
Exemple #20
0
void Win32Process::Monitor()
{
    STARTUPINFO startupInfo;
    startupInfo.cb          = sizeof(STARTUPINFO);
    startupInfo.lpReserved  = NULL;
    startupInfo.lpDesktop   = NULL;
    startupInfo.lpTitle     = NULL;
    startupInfo.dwFlags     = STARTF_FORCEOFFFEEDBACK | STARTF_USESTDHANDLES;
    startupInfo.cbReserved2 = 0;
    startupInfo.lpReserved2 = NULL;

    HANDLE hProc = GetCurrentProcess();
    DuplicateHandle(hProc, in->GetReadHandle(), hProc, &startupInfo.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
    CloseHandle(in->GetReadHandle());
    DuplicateHandle(hProc, out->GetWriteHandle(), hProc, &startupInfo.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
    CloseHandle(out->GetWriteHandle());
    DuplicateHandle(hProc, err->GetWriteHandle(), hProc, &startupInfo.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS);
    CloseHandle(err->GetWriteHandle());

    std::string commandLine = command;
    for (std::vector<std::string>::const_iterator it = arguments.begin(); it != arguments.end(); ++it)
    {
        commandLine.append(" ");
        commandLine.append(*it);
    }

    logger->Debug("Launching: %s", commandLine.c_str());

    PROCESS_INFORMATION processInfo;
    BOOL rc = CreateProcessA(NULL,
                             (char*)commandLine.c_str(),
                             NULL,
                             NULL,
                             TRUE,
                             0,
                             NULL,
                             NULL,
                             &startupInfo,
                             &processInfo);

    CloseHandle(startupInfo.hStdInput);
    CloseHandle(startupInfo.hStdOutput);
    CloseHandle(startupInfo.hStdError);

    if (!rc) {
        std::string message = "Error launching: " + commandLine;
        logger->Error(message);
        throw ValueException::FromString(message);
    }
    else {
        StartThreads();
        CloseHandle(processInfo.hThread);
        this->pid = processInfo.dwProcessId;
        this->process = processInfo.hProcess;
        this->Set("pid", Value::NewInt(this->pid));
        this->running = true;
        this->Set("running", Value::NewBool(true));
    }

    while (true) {
        DWORD rc = WaitForSingleObject(this->process, 250);
        if (rc == WAIT_OBJECT_0) {
            break;
        }
        if (rc == WAIT_ABANDONED) {
            break;
        }
        else continue;
    }

    logger->Debug("finally exited it looks like");

    DWORD exitCode;
    if (GetExitCodeProcess(this->process, &exitCode) == 0) {
        throw ValueException::FromString("Cannot get exit code for process");
    }
    this->exitCode = exitCode;
    this->Set("exitCode", Value::NewInt(this->exitCode));

    this->parent->Terminated(this);
    this->Set("running", Value::NewBool(false));

    logger->Debug("Invoking onexit");
    InvokeOnExit();
}
void StkThreadGuiManager::StartAllThreads()
{
	StartThreads(true);
}
Exemple #22
0
int __cdecl main(int argc, char **argv) 
{
	ULONGLONG ttstart, ttend;

	params_tx = &(params[0]);
	params_rx = &(params[1]);

	// Initialize the global parameters
	try_parse_args(params, argc, argv);


	printf("Setting up threads...\n");

	if (mac_type == 0)
	{
		// **** Single-thread MAC

		// Initialize various parameters
		init_mac_1thread();


		//SINGLE MODULE CODE: int no_threads = wpl_set_up_threads_tx(User_Routines);
		int no_threads = SetUpThreads_1t(User_Routines);
		StartThreads(&ttstart, &ttend, &(params_tx->measurementInfo.tsinfo), no_threads, User_Routines);

		printf("Time Elapsed: %ld us \n",
			SoraTimeElapsed((ttend / 1000 - ttstart / 1000), &(params_tx->measurementInfo.tsinfo)));

		if (params_tx->latencySampling > 0)
		{
			printf("Min write latency: %ld, max write latency: %ld\n", (ulong)params_tx->measurementInfo.minDiff, (ulong)params_tx->measurementInfo.maxDiff);
			printf("CDF: \n   ");
			unsigned int i = 0;
			while (i < params_tx->measurementInfo.aDiffPtr)
			{
				printf("%ld ", params_tx->measurementInfo.aDiff[i]);
				if (i % 10 == 9)
				{
					printf("\n   ");
				}
				i++;
			}
			printf("\n");
		}
	}
	else
	{
		// **** TX/RX(2)-threaded MAC

		// Initialize various parameters
		init_mac_2threads();


		//SINGLE MODULE CODE: int no_threads = wpl_set_up_threads_tx(User_Routines);
		int no_threads = SetUpThreads_2t(User_Routines);
		StartThreads(&ttstart, &ttend, &(params_tx->measurementInfo.tsinfo), no_threads, User_Routines);

		printf("Time Elapsed: %ld us \n",
			SoraTimeElapsed((ttend / 1000 - ttstart / 1000), &(params_tx->measurementInfo.tsinfo)));

	}

	// Free thread separators
	// NB: these are typically allocated in blink_set_up_threads
	ts_free();



	// Start Sora HW
	if (params_rx->inType == TY_SORA || params_tx->outType == TY_SORA)
	{
		RadioStop(*params_tx);
	}
	// Start NDIS
	if (params_tx->inType == TY_IP)
	{
		if (hUplinkThread != NULL)
		{
			// Sora cleanup.
			SoraUThreadStop(hUplinkThread);
			SoraUThreadFree(hUplinkThread);
		}
		SoraUDisableGetTxPacket();
		// Winsock cleanup.
		closesocket(ConnectSocket);
		WSACleanup();

	}

	if (params_rx->outType == TY_IP)
	{
		// To be implemented
		/*
		if (hUplinkThread != NULL)
		{
			// Sora cleanup.
			SoraUThreadStop(hUplinkThread);
			SoraUThreadFree(hUplinkThread);
		}
		SoraUDisableGetTxPacket();
		// Winsock cleanup.
		closesocket(ConnectSocket);
		WSACleanup();
		*/
	}


	return 0;
}
void TestMovingCode(RPageMove& aPagemove, TTestFunction aFunc, TBool aPaged=EFalse)
	{
	TUint8* firstpage = (TUint8*)_ALIGN_DOWN((TLinAddr)aFunc, PageSize);
	RThread thread;
	thread.Open(RThread().Id());
	SPinThreadArgs threadArgs;
	threadArgs.iLinAddr = (TLinAddr)firstpage;
	threadArgs.iTestFunc = aFunc;
	threadArgs.iParentThread = thread;
	threadArgs.iRealtimeState = User::ERealtimeStateOff;

	TMovingPinStage endStage = EMovingPinStages;
	if (!gPinningSupported)
		endStage = EVirtualPinning;

	for (TUint state = ENoPinning; state < (TUint)endStage; state++)
		{
		TThreadFunction threadFunc = NULL;
		switch (state)
			{
			case ENoPinning:
				test.Printf(_L("Attempt to move pages while they are being executed\n"));
				threadFunc = &RunCodeThread;
				test_Equal(KArbitraryNumber, aFunc()); // Ensure the page is paged in.
				break;
			case EVirtualPinning:
				test.Printf(_L("Attempt to move pages while they are being virtually pinned\n"));
				threadFunc = &VirtualPinPage;
				break;
			case EPhysicalPinning:
				test.Printf(_L("Attempt to move pages while they are being physically pinned\n"));
				threadFunc = &PhysicalPinPage;
				break;
			}
		ThreadDie = EFalse;
		TUint numThreads = (NumberOfCpus > 1) ? NumberOfCpus - 1 : 1;
		RThread* codeRunThread = new RThread[numThreads];
		TRequestStatus* s = new TRequestStatus[numThreads];
		StartThreads(numThreads, codeRunThread, s, threadFunc, threadArgs);

		_T_PRINTF(_L("Move first code page repeatedly\n"));
		test_Equal(KArbitraryNumber, aFunc());	
		TBool inuse=EFalse, success=EFalse;
		for (TInt i=0; i < Repitions; i++)
			{
			TInt r = aPagemove.TryMovingUserPage(firstpage, ETrue);
			if (i == 0)
				{// If this is the first run allow the pinning threads to 
				// unpin the memory now that we've definitely done at least 
				// one page move with the page pinned.
				_T_PRINTF(_L("signal to child\n"));
				RThread::Rendezvous(KErrNone);
				}
			switch (r)
				{
				case KErrInUse:
					inuse=ETrue;
					break;
				case KErrArgument:
					// The page was paged out, this should only happen for paged code.
					test(aPaged);
					break;
				default:
					test_KErrNone(r);
					success=ETrue;
					break;
				}
			}
		// Physical pinning or adding a new pinning while a page is being moved
		// should prevent code pages being moved.
		switch (state)
		{
			case ENoPinning :			
				test(!inuse || aPaged);	// Stealing may get KErrInUse but this should only happen for paged code.
			case EVirtualPinning :
				test(success);
				break;
			case EPhysicalPinning :
				break;
		}

		ThreadDie = ETrue;
		EndThreads(numThreads, codeRunThread, s);

		_T_PRINTF(_L("Validate page data\n"));
		test_Equal(KArbitraryNumber, aFunc());		
		}
	thread.Close();
	}
void TestPageTableDiscard(RPageMove& pagemove, TUint8* array, TUint size)
	{
	_T_PRINTF(_L("Fill the array with some data\n"));
	for (TUint i=0; i<size; i++) array[i] = i*i;

	TUint8* firstpage = (TUint8*)_ALIGN_DOWN((TLinAddr)array, PageSize);
	RThread thread;
	thread.Open(RThread().Id());
	SPinThreadArgs threadArgs;
	threadArgs.iLinAddr = (TLinAddr)array;
	threadArgs.iParentThread = thread;
	threadArgs.iRealtimeState = User::ERealtimeStateOff;

	TMovingPinStage endStage = EMovingPinStages;
	if (!gPinningSupported)
		endStage = EVirtualPinning;
	
	for (TUint pageTableInfo = 0; pageTableInfo < 2; pageTableInfo++)
		{
		for (TUint state = ENoPinning; state < (TUint)endStage; state++)
			{
			TThreadFunction threadFunc = NULL;
			if (!pageTableInfo)
			{
			switch (state)
				{
				case ENoPinning:
					test.Printf(_L("Attempt to move page tables whilst the pages they map are being modified\n"));
					threadFunc = &ReadWriteByte;
					break;
				case EVirtualPinning:
					test.Printf(_L("Attempt to move page tables whilst the pages they map are being virtually pinned\n"));
					threadFunc = &VirtualPinPage;
					break;
				case EPhysicalPinning:
					test.Printf(_L("Attempt to move page tables whilst the pages they map are being physically pinned\n"));
					threadFunc = &PhysicalPinPage;
					break;
				}
			}
			else
			{
			switch (state)
				{
				case ENoPinning:
					test.Printf(_L("Attempt to move page table infos whilst pages they refer to are being modified\n"));
					threadFunc = &ReadWriteByte;
					break;
				case EVirtualPinning:
					test.Printf(_L("Attempt to move page table infos whilst pages they refer to are being virtually pinned\n"));
					threadFunc = &VirtualPinPage;
					break;
				case EPhysicalPinning:
					test.Printf(_L("Attempt to move page table infos whilst pages they refer to are being physically pinned\n"));
					threadFunc = &PhysicalPinPage;
					break;
				}
			}
			ThreadDie = EFalse;
			TUint numThreads = (NumberOfCpus > 1) ? NumberOfCpus - 1 : 1;
			RThread* threads = new RThread[numThreads];
			TRequestStatus* s = new TRequestStatus[numThreads];
			StartThreads(numThreads, threads, s, threadFunc, threadArgs);

			_T_PRINTF(_L("Move first array page repeatedly\n"));
			TUint inuse = 0;
			for (TInt i=0; i < Repitions; i++)
				{
				TInt r;
				if (!pageTableInfo)
					r = pagemove.TryMovingPageTable(firstpage);
				else
					r = pagemove.TryMovingPageTableInfo(firstpage);					
				if (i == 0)
					{// If this is the first run allow the pinning threads to 
					// unpin the memory now that we've definitely done at least 
					// one page move with the page pinned.
					_T_PRINTF(_L("signal to child\n"));
					RThread::Rendezvous(KErrNone);
					}
				switch (r)
					{
					case KErrInUse:
						inuse++;
						break;
					case KErrNotFound:
						// The page table or page table info page was paged out.
						break;
					default:
						test_KErrNone(r);
						break;
					}
				}
			test.Printf(_L("inuse %d\n"),inuse);
			// A virtually pinned page should always return KErrInUse at least once.
			test(state != EVirtualPinning || inuse);

			ThreadDie = ETrue;
			EndThreads(numThreads, threads, s);

			_T_PRINTF(_L("Validate page data\n"));
			for (TUint i=0; i<size; i++)
				test_Equal((TUint8)(i*i), array[i]);
			}
		}
	thread.Close();
	}
Exemple #25
0
ThreadPool::ThreadPool(const u32 numThreads)
{
	StartThreads(numThreads);
}
Exemple #26
0
void EventDlg_OnCommand(HWND hDlg, int id, HWND hwndCtl, UINT codeNotify)
{
	int rc;

	switch (id)
	{
	case IDC_AUTOMATIC:
		KillThreads();
		if (hEventObject) rc = CloseHandle(hEventObject);
		MTVERIFY( hEventObject = CreateEvent(NULL,	// Security
										FALSE,		// Automatic (FALSE = not manual)
										0,			// Clear on creation
										"EventTest")// Name of object
									);
		// CreateEvent ALWAYS sets the last error
		if (GetLastError() == ERROR_ALREADY_EXISTS)
			AddToList("WARNING: Event wasn't destroyed");
		StartThreads();
		AddToList("Event set to AUTOMATIC");
		break;

	case IDC_MANUAL:
		KillThreads();
		if (hEventObject) rc = CloseHandle(hEventObject);
		MTVERIFY( hEventObject = CreateEvent(NULL,	// Security
										TRUE,		// Manual
										0,			// Clear on creation
										"EventTest")// Name of object
									);
		if (GetLastError() == ERROR_ALREADY_EXISTS)
			AddToList("Reusing old event");
		StartThreads();
		AddToList("Event set to MANUAL");
		break;

	case IDC_SIGNAL:
		MTVERIFY( SetEvent(hEventObject) );
		break;

	case IDC_RESET:
		MTVERIFY( ResetEvent(hEventObject) );
		break;

	case IDC_PULSE:
		MTVERIFY( PulseEvent(hEventObject) );
		break;

	case IDC_CLEAR:
		ListBox_ResetContent(GetDlgItem(hDlg, IDC_RESULTS));
		break;

	case IDCANCEL:
	case IDM_EXIT:
		PostMessage(GetParent(hDlg),WM_DESTROY, (WPARAM)0, (LPARAM)0);
		DestroyWindow(hDlgMain);
		hDlgMain = NULL;
		break;
		
	default:
		break;
	}
}