void run(){
    while(1){
      yield();
      yieldCnt++;
      yieldGlobal++;
      // displays every 100000 times
      if((yieldCnt%100000) == 0){
        long long timeNow = NOW();
        printProtect.enter();
	      PRINTF(" %s: ", getName());
	      PRINTF("cnt = %ld, ", (long)yieldCnt);
	      PRINTF("totalyiels = %ld, ", (long)getScheduleCounter());
	      PRINTF("Time = %3.9f, ", (double)timeNow/SECONDS);
	      PRINTF("nsec/dispatchCnt = %ld  ", (long)( ((double)timeNow / (double)getScheduleCounter()) * NANOSECONDS ) );
	      PRINTF("nsec/yieldCnt = %ld\n", (long)( ((double)timeNow / (double)yieldGlobal         ) * NANOSECONDS ) );
        printProtect.leave();
      }
    }	
  }
Exemple #2
0
void * wait(void *ptr)
{
    Semaphore *sem;
    sem = (Semaphore*) ptr;
    pthread_t   tid;
    tid = pthread_self();
    
    pthread_mutex_lock(&main_mutex);
    cout<<tid<<":start to wait"<<endl;
    pthread_mutex_unlock(&main_mutex);
    
    sem->P();
   
    pthread_mutex_lock(&main_mutex);
    cout<<tid<<":finish waiting"<<endl;
    pthread_mutex_unlock(&main_mutex);
    
    return NULL;
}
Exemple #3
0
int EthernetInterface::connect(unsigned int timeout_ms) {
    eth_arch_enable_interrupts();

    int inited;
    if (use_dhcp) {
        dhcp_start(&netif);
        
        // Wait for an IP Address
        // -1: error, 0: timeout
        inited = netif_up.wait(timeout_ms);
    } else {
        netif_set_up(&netif);
        
        // Wait for the link up
        inited = netif_linked.wait(timeout_ms);
    }
    
    return (inited > 0) ? (0) : (-1);
}
// This helper function is a deadlock-safe method of waiting on a semaphore in a pxThread.  If the
// thread is terminated or canceled by another thread or a nested action prior to the semaphore being
// posted, this function will detect that and throw a CancelEvent exception is thrown.
//
// Note: Use of this function only applies to semaphores which are posted by the worker thread.  Calling
// this function from the context of the thread itself is an error, and a dev assertion will be generated.
//
// Exceptions:
//   This function will rethrow exceptions raised by the persistent thread, if it throws an error
//   while the calling thread is blocking (which also means the persistent thread has terminated).
//
void Threading::pxThread::WaitOnSelf( Semaphore& sem ) const
{
	if( !AffinityAssert_DisallowFromSelf(pxDiagSpot) ) return;

	while( true )
	{
		if( sem.WaitWithoutYield( wxTimeSpan(0, 0, 0, 333) ) ) return;
		_selfRunningTest( L"semaphore" );
	}
}
void Win32SyncManager::ThreadBegin(Semaphore sem){
	sem.Down();
	OnWakeup();
	TlsSetValue(tlsCurrentTaskId, (LPVOID)runningTid);
	Chess::TaskBegin();
#ifndef UNDER_CE
	//A thread starts in an alertable state (i.e. Executes APCs that are queued before starting)
	WrappersOnAlertableState(runningTid);
#endif
}
Exemple #6
0
  void worker_done_with_task() {
    // Mark that the worker is done with the task.
    // The worker is not allowed to read the state variables after this line.
    uint not_finished = (uint) Atomic::add(-1, (volatile jint*)&_not_finished);

    // The last worker signals to the coordinator that all work is completed.
    if (not_finished == 0) {
      _end_semaphore->signal();
    }
  }
Exemple #7
0
int main(int argc, char **argv)
{
	char buffer[TAM_BUFFER];

	if (argc != 2) {
		strcpy (buffer, "Error: Cantidad de parametros invalida\n");
		write (fileno(stderr),buffer, strlen(buffer));
		exit(1);
	}
	
	int cantProcesos = 0;
	sscanf(argv[1] , "%d", &cantProcesos);
	
	// Creando semaforo de control de acceso a la memoria compartida
	Semaphore semControl = Semaphore();	
	semControl.createSemaphore((char *)DIRECTORY, ID_SEMCONTROL, 1);
	semControl.initializeSemaphore(0, 1);

	// Creando semaforos de control de los procesos
	Semaphore semProductores = Semaphore();
	semProductores.createSemaphore((char *)DIRECTORY, ID_SEMPRODUCTORES, cantProcesos);
	for (int nroSemaforo = 0; nroSemaforo < cantProcesos; nroSemaforo++) {
	 	semProductores.initializeSemaphore(nroSemaforo, 1);
	}
	
	// Creando la memoria compartida
	CountingSharedMemory shMem = CountingSharedMemory();
	shMem.createSharedMemory((char *)DIRECTORY, ID_SHMEM);
	semControl.wait(0);
	{	
		int p = 0;
		shMem.writeInfo(&p);
	}
	semControl.signal(0);
		
	for (int i = 0; i < cantProcesos; i++) {
		pid_t pid = fork();
		if (pid == 0) {
			char nroProductor[TAM_BUFFER];
			sprintf(nroProductor,"%d",i);
						
			execlp("./productor", "productor", nroProductor, argv[1], (char *) 0);
			sprintf(buffer, "Launcher Error: %s\n", strerror(errno));
			write(fileno(stdout), buffer, strlen(buffer));
		}
		//sleep (1);
	}		
	
	sprintf(buffer, "Launcher Terminado \n");
	write(fileno(stdout), buffer, strlen(buffer));
			
	return 0;
}
bool NetworkClock::read(ConnectionReader& reader) {
    Bottle bot;
    bool ok = bot.read(reader);

    if(closing)
    {
        _time = -1;
        return false;
    }

    if (!ok && !closing)
    {
        YARP_ERROR(Logger::get(), "Error reading clock port");
        return false;
    }

    timeMutex.lock();
    sec = bot.get(0).asInt32();
    nsec = bot.get(1).asInt32();
    _time = sec + (nsec*1e-9);
    initted = true;
    timeMutex.unlock();

    listMutex.lock();
    Waiters* waiters = static_cast<Waiters*>(pwaiters);
    Waiters::iterator waiter_i;

    waiter_i = waiters->begin();
    while (waiter_i != waiters->end())
    {
        if (waiter_i->first - _time < 1E-12 )
        {
            Semaphore *waiterSemaphore = waiter_i->second;
            waiter_i = waiters->erase(waiter_i);
            if (waiterSemaphore)
                waiterSemaphore->post();
        }
        else
            ++waiter_i;
    }
    listMutex.unlock();
    return true;
}
// WaitForSignal
//------------------------------------------------------------------------------
void TestSemaphore::WaitForSignal() const
{
    Semaphore s;

    // Create a thread which will signal the Semaphore
    Thread::ThreadHandle h = Thread::CreateThread( WaitForSignal_Thread, "Test::WaitForSignal", ( 32 * KILOBYTE ), &s );

    // Wait or the expected signal count
    for ( size_t i=0; i<100; ++i )
    {
        s.Wait();
    }

    // Cleanup thread
    bool timedOut;
    Thread::WaitForThread( h, 1000, timedOut );
    TEST_ASSERT( timedOut == false );
    Thread::CloseHandle( h );
}
Exemple #10
0
// Filter speed with averaging filter
// The last 3 speeds are used to caculate an average
// Both the speed and the average speed semaphores are used
// Repetition rate 5 Hz = 0.2 seconds
void getAverageSpeed(void const *args) {
    while (true) {
        int sum = 0; 
        Speed_SEM.wait();
        AVR_SPEED_SEM.wait();
        
        // get the sum of the last 3 speeds
        for(int i =0; i< sampleNumber ; i++)
        {
            sum += speeds[i];
        }
        // get the average of the last 3 speeds
        averageSpeed = sum/sampleNumber;
        
        AVR_SPEED_SEM.release();
        Speed_SEM.release();
        Thread::wait(200);
    } 
}
Exemple #11
0
void CpDevices::Clear()
{
    iLock.Wait();
    const TUint count = (TUint)iList.size();
    for (TUint i=0; i<count; i++) {
        iList[i]->RemoveRef();
    }
    iList.clear();
    (void)iSem.Clear();
    iLock.Signal();
}
Exemple #12
0
  WorkData worker_wait_for_task() {
    // Wait for the coordinator to dispatch a task.
    _start_semaphore->wait();

    uint num_started = (uint) Atomic::add(1, (volatile jint*)&_started);

    // Subtract one to get a zero-indexed worker id.
    uint worker_id = num_started - 1;

    return WorkData(_task, worker_id);
  }
Exemple #13
0
int EthernetInterface::connect(unsigned int timeout_ms) {
    NVIC_SetPriority(ENET_IRQn, ((0x01 << 3) | 0x01));
    NVIC_EnableIRQ(ENET_IRQn);
    
    int inited;
    if (use_dhcp) {
        dhcp_start(&lpcNetif);
        
        // Wait for an IP
        // -1: error, 0: timeout
        inited = netif_up.wait(timeout_ms);
    } else {
        netif_set_up(&lpcNetif);
        
        // Wait for the link up
        inited = netif_linked.wait(timeout_ms);
    }
    
    return (inited > 0) ? (0) : (-1);
}
Exemple #14
0
ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) {
    Semaphore* semaphore = g_handle_table.Get<Semaphore>(handle).get();
    if (semaphore == nullptr)
        return InvalidHandle(ErrorModule::Kernel);

    if (semaphore->max_count - semaphore->available_count < release_count)
        return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel, 
                          ErrorSummary::InvalidArgument, ErrorLevel::Permanent);

    *count = semaphore->available_count;
    semaphore->available_count += release_count;

    // Notify some of the threads that the semaphore has been released
    // stop once the semaphore is full again or there are no more waiting threads
    while (!semaphore->ShouldWait() && semaphore->WakeupNextThread() != nullptr) {
        semaphore->Acquire();
    }

    return RESULT_SUCCESS;
}
Exemple #15
0
static void init_netif(ip_addr_t *ipaddr, ip_addr_t *netmask, ip_addr_t *gw) {
    tcpip_init(tcpip_init_done, NULL);
    tcpip_inited.wait();
    
    memset((void*) &lpcNetif, 0, sizeof(lpcNetif));
    netif_add(&lpcNetif, ipaddr, netmask, gw, NULL, lpc_enetif_init, tcpip_input);
    netif_set_default(&lpcNetif);
    
    netif_set_link_callback  (&lpcNetif, netif_link_callback);
    netif_set_status_callback(&lpcNetif, netif_status_callback);
}
int ReceiveThread::run()
{
    ISocket * socket = ISocket::create(3456);
    ISocket * client = socket->accept();
    StringBuffer result;
    readResults(client, parallelBlocked, false, result, nullptr, 0);
    client->Release();
    socket->Release();
    finishedReading.signal();
    return 0;
}
Exemple #17
0
 virtual bool read(ConnectionReader& connection) {
     double now = Time::now();
     Bottle b;
     bool ok = b.read(connection);
     if (ok) {
         mutex.wait();
         ct++;
         if (ct>1) {
             double dt = now - lastTime;
             period.add(dt);
         }
         lastTime = now;
         printf("Period is %g +/- %g (%d)\n",
                period.mean(),
                period.deviation(),
                ct);
         mutex.post();
     }
     return ok;
 }
Exemple #18
0
int main (int argc, char* argv[])
{
    Semaphore sem;

    uxmpp_log_info (THIS_FILE, "Wait for semaphore");
    sem.wait (chrono::milliseconds(500));
    //sem.wait ();
    uxmpp_log_info (THIS_FILE, "Done waiting");

    uxmpp_log_info (THIS_FILE, "Wait for semaphore");
    sem.post ();
    sem.post ();
    sem.wait ();
    uxmpp_log_info (THIS_FILE, "Done waiting");
    uxmpp_log_info (THIS_FILE, "Wait for semaphore");
    sem.wait (chrono::milliseconds(500));
    uxmpp_log_info (THIS_FILE, "Done waiting");

    return 0;
}
	int ANativeWindowDisplayAdapter::enableDisplay(int width, int height, struct timeval *refTime, S3DParameters *s3dParams)
	{
		Semaphore sem;
		TIUTILS::Message msg;

		LOG_FUNCTION_NAME;

		if ( mDisplayEnabled )
		{
			LOGINFO("Display is already enabled");
			LOG_FUNCTION_NAME_EXIT;

			return NO_ERROR;
		}

		//Send START_DISPLAY COMMAND to display thread. Display thread will start and then wait for a message
		sem.Create();
		msg.command = DisplayThread::DISPLAY_START;

		// Send the semaphore to signal once the command is completed
		msg.arg1 = &sem;

		///Post the message to display thread
		mDisplayThread->msgQ().put(&msg);

		///Wait for the ACK - implies that the thread is now started and waiting for frames
		sem.Wait();

		// Register with the frame provider for frames
		mFrameProvider->enableFrameNotification(CameraFrame::PREVIEW_FRAME_SYNC);

		mDisplayEnabled = true;
		mPreviewWidth = width;
		mPreviewHeight = height;

		LOGINFO("mPreviewWidth = %d mPreviewHeight = %d", mPreviewWidth, mPreviewHeight);

		LOG_FUNCTION_NAME_EXIT;

		return NO_ERROR;
	}
    void onRead(Sound& sound)
     {
       
        #ifdef TEST
        //this block can be used to measure time elapsed between two sound packets
        static double t1= yarp::os::Time::now();
        static double t2= yarp::os::Time::now();
        t1= yarp::os::Time::now();
        printf("onread %f\n", t2-t1);
        t2 = yarp::os::Time::now();
        #endif

        int ct = port.getPendingReads();
        //printf("pending reads %d\n", ct);
        while (ct>padding) {
            ct = port.getPendingReads();
            printf("Dropping sound packet -- %d packet(s) behind\n", ct);
            port.read();
        }
        mutex.wait();
        /*
          if (muted) {
          for (int i=0; i<sound.getChannels(); i++) {
          for (int j=0; j<sound.getSamples(); j++) {
          sound.put(0,j,i);
          }
          }
          }
        */
        if (!muted) {
            if (put!=NULL) {
                put->renderSound(sound);
            }
        }
        if (saving) {
            saveFrame(sound);
        }

        mutex.post();
        Time::yield();
    }
Exemple #21
0
void TestThreading::testAtomicSemaphoreThread()
{
    Atomic<u32> val;
    Semaphore trigger;
    static const u8 num_threads = 4;

    AtomicTestThread *threads[num_threads];
    for (u8 i = 0; i < num_threads; ++i) {
        threads[i] = new AtomicTestThread(val, trigger);
        UASSERT(threads[i]->start());
    }

    trigger.post(num_threads);

    for (u8 i = 0; i < num_threads; ++i) {
        threads[i]->wait();
        delete threads[i];
    }

    UASSERT(val == num_threads * 0x10000);
}
Exemple #22
0
// Flash appropriate indicator LEDs at a rate of 1Hz
// input semaphore used so value doesnt change
// Repetition rate 1 Hz = 1 seconds
void flashIndicator()
{
    INPUT_SEM.wait();
    // only happens if a single light or no light is on
    if(!(leftLightState && rightLightState))
    { 
        if(leftLightState)
        {
            // ! used to flip value to create flashing
            leftIndicator = !leftIndicator;
            rightIndicator = 0;
        }            
        if(rightLightState) 
        {
            leftIndicator = 0;
            // ! used to flip value to create flashing
            rightIndicator = !rightIndicator;
         }
     }
     INPUT_SEM.release();
}
Exemple #23
0
void * sig(void *ptr)
{
    sleep(1);
    Semaphore *sem;

    sem = (Semaphore*) ptr; 
    pthread_t   tid;
    tid = pthread_self();
    
    pthread_mutex_lock(&main_mutex);
    cout<<tid<<":start to sig"<<endl;
    pthread_mutex_unlock(&main_mutex);
    
    sem->V();
    
    pthread_mutex_lock(&main_mutex);
    cout<<tid<<":finish sig"<<endl;
    pthread_mutex_unlock(&main_mutex);
    
    return NULL;
}
  void run() {
     suspendCallerUntil(1*SECONDS);
     protector.enter(); 
       xprintf("hier %s\n", name);
       xprintf("at %ld,%09ld: thread started ", SPLIT_SEC_NS(NOW()) ) ;
       xprintf("- scheduleCounter= %ld\n", (long) Scheduler::getScheduleCounter());
     protector.leave();

     for(long i=0; i < max; i++){
        protector.enter(); 
          counter++;
        protector.leave();
     }

     protector.enter(); 
       xprintf("hier %s\n", name);
       xprintf("at %ld,%09ld:", SPLIT_SEC_NS(NOW()));
       xprintf("counter= %ld ", counter);
       xprintf("- scheduleCounter= %ld\n", (long) Scheduler::getScheduleCounter());
     protector.leave();
    
     while(1) {
       xprintf(" %x, = %s beendet semaphore daten: \n", (int)this, name);
       //xprintf(" owenr %x, entercnt =%d\n", (int)protector.owner, (int)protector.ownerEnterCnt); // variables are private
       suspendCallerUntil();
     }
  }
Exemple #25
0
int main(int argc, char **argv)
{
	char buffer[255];

	if (argc != 2) {
		strcpy (buffer, "Error: Cantidad de parametros invalida\n");
		write (fileno(stderr),buffer, strlen(buffer));
		exit(1);
	}
	
	int cantProcesos = 0;
	sscanf(argv[1] , "%d", &cantProcesos);
	
	
	// Obteniendo semaforo de control de acceso a la memoria compartida
	Semaphore semControl = Semaphore();	
	semControl.getSemaphore((char *)DIRECTORY, ID_SEMCONTROL, 1);
	semControl.destroy();

	// Obteniendo semaforos de control de los procesos
	Semaphore semProductores = Semaphore();
	semProductores.getSemaphore((char *)DIRECTORY, ID_SEMPRODUCTORES, cantProcesos);
	semProductores.destroy();
	
	// Obteniendo la memoria compartida	
	CountingSharedMemory shMem = CountingSharedMemory();
	shMem.getSharedMemory((char *)DIRECTORY, ID_SHMEM);
	shMem.destroy();
	
	return 0;
}
Exemple #26
0
void SuiteAlive::Test()
{
    Blocker* blocker = new Blocker;
    CpListenerBasic* listener = new CpListenerBasic;
    NetworkAdapter* nif = Stack::NetworkAdapterList().CurrentAdapter(kAdapterCookie);
    SsdpListenerMulticast* listenerMulticast = new SsdpListenerMulticast(nif->Address());
    nif->RemoveRef(kAdapterCookie);
    TInt listenerId = listenerMulticast->AddNotifyHandler(listener);
    listenerMulticast->Start();

    DviDevice* device = new DviDeviceStandard(gNameDevice1);
    device->SetAttribute("Upnp.Domain", "a.b.c");
    device->SetAttribute("Upnp.Type", "type1");
    device->SetAttribute("Upnp.Version", "1");
    AddService(device, new DviService("a.b.c", "service1", 1));
    AddService(device, new DviService("a.b.c", "service2", 1));
    device->SetEnabled();
    blocker->Wait(1);
    /* we expect 5 messages but linux sometimes reports multicast messages from
      all subnets to listeners on any single subnet so just check that we've
      received a multiple of 5 messages */
      
    TEST(listener->TotalMessages() > 0);
    TEST(listener->TotalMessages() % 5 == 0);

    Functor disabled = MakeFunctor(*this, &SuiteAlive::Disabled);
    device->SetDisabled(disabled);
    iSem.Wait();
    blocker->Wait(1); /* semaphore being signalled implies that the device has been
                         disabled.  We may require some extra time to receive the
                         multicast byebye confirming this */
    TEST(listener->TotalMessages() == 0);

    device->SetEnabled();
    blocker->Wait(1);
    TEST(listener->TotalMessages() > 0);
    TEST(listener->TotalMessages() % 5 == 0);

    // Control point doesn't process ssdp:update notifications
    // check that updates are basically working by counting the extra alive messages instead
    TUint oldTotal = listener->TotalMessages();
    device->SetAttribute("Upnp.TestUpdate", "1");
    blocker->Wait(1);
    TEST(listener->TotalMessages() > oldTotal);
    TEST(listener->TotalMessages() % 5 == 0);

    device->Destroy();
    listenerMulticast->RemoveNotifyHandler(listenerId);
    delete listenerMulticast;
    delete listener;
    delete blocker;
}
Exemple #27
0
ResultCode ReleaseSemaphore(s32* count, Handle handle, s32 release_count) {
    Semaphore* semaphore = g_object_pool.Get<Semaphore>(handle);
    if (semaphore == nullptr)
        return InvalidHandle(ErrorModule::Kernel);

    if (semaphore->max_count - semaphore->available_count < release_count)
        return ResultCode(ErrorDescription::OutOfRange, ErrorModule::Kernel, 
                          ErrorSummary::InvalidArgument, ErrorLevel::Permanent);

    *count = semaphore->available_count;
    semaphore->available_count += release_count;

    // Notify some of the threads that the semaphore has been released
    // stop once the semaphore is full again or there are no more waiting threads
    while (!semaphore->waiting_threads.empty() && semaphore->IsAvailable()) {
        Kernel::ResumeThreadFromWait(semaphore->waiting_threads.front());
        semaphore->waiting_threads.pop();
        --semaphore->available_count;
    }

    return RESULT_SUCCESS;
}
Exemple #28
0
 void push(const void *row)
 {   
     CriticalBlock b2(fullCrit); // exclusivity for totSize / full
     if (stopped) return;
     rows.enqueue(row);
     totSize += thorRowMemoryFootprint(row);
     while (totSize > FUNNEL_MIN_BUFF_SIZE)
     {
         full = true;
         CriticalUnblock b(fullCrit);
         fullSem.wait(); // block pushers on crit
     }
 }
Exemple #29
0
	WaitResult_t QueueImpl::get(Message& message, int64_t timeout_msec)
	{
		LogTraceObj("['%s'] (0x%I64X%s)", name.c_str(), timeout_msec, timeout_msec == TIMEOUT_INFINITE ? " INFINITE" : "");
		auto waitResult = se.try_lock_ex(timeout_msec);
		if (waitResult == WaitResult_t::SUCCESS) {
			auto guard = simstd::auto_lock(cs);
			message = simstd::move(front());
			erase(cbegin());
		}
		LogAttenIf(waitResult != WaitResult_t::SUCCESS, "['%s'] -> '%S'", name.c_str(), totext::c_str(waitResult));
		LogDebugIf(waitResult == WaitResult_t::SUCCESS, "['%s'] -> '%S' Message(0x%IX(%Iu, %Iu, %Iu))", name.c_str(), totext::c_str(waitResult), message->get_code(), message->get_a(), message->get_b(), message->get_c());
		return waitResult;
	}
Exemple #30
0
void CpDevices::Added(CpDevice& aDevice)
{
    iLock.Wait();
    const Brx& udn = aDevice.Udn();
    if (udn == gNameDevice1 || udn == gNameDevice1_1 || udn == gNameDevice1_2 || udn == gNameDevice2) {
        iList.push_back(&aDevice);
        aDevice.AddRef();
    }
    if ((TUint)iList.size() == iTargetCount) {
        iSem.Signal();
    }
    iLock.Signal();
}