Exemplo n.º 1
0
bool
KRT2Device::Send(const uint8_t *msg, unsigned msg_size,
                 OperationEnvironment &env)
{
  //! Number of tries to send a message
  unsigned retries = NR_RETRIES;

  assert(msg_size > 0);

  do {
    response_mutex.Lock();
    response = NO_RSP;
    response_mutex.Unlock();
    // Send the message
    if (!port.FullWrite(msg, msg_size, env, CMD_TIMEOUT))
      return false;
    // Wait for the response
    response_mutex.Lock();
    rx_cond.timed_wait(response_mutex, CMD_TIMEOUT);
    auto _response = response;
    response_mutex.Unlock();

    if (_response == ACK)
      // ACK received, finish
      return true;

    // No ACK received, retry
    retries--;
  } while (retries);

  return false;
}
Exemplo n.º 2
0
int main(){
	Mutex mutex;
	cout << mutex.Lock() << endl;
	cout << mutex.Unlock() << endl;
	cout << mutex.Unlock() << endl;
	cout << mutex.Lock() << endl;
    return 0;
}
Exemplo n.º 3
0
	bool Condition::wait(Mutex& mutex, long timeout)
	{
#if defined(WIN32)

		m_impl -> PreWait();
		mutex.Unlock();

		try
		{
			bool rc = m_impl -> Wait(timeout);
			mutex.Lock();
			return rc;
		}
		catch(...)
		{
			mutex.Lock();
			throw;
		}
#else

		int ret = 0;
		if (timeout < 0)
		{
			ret = pthread_cond_wait(&m_cond, &mutex.m_mutex);
		}
		else
		{
			struct timespec abstime = CalcAbsTime(timeout);
			ret = pthread_cond_timedwait(&m_cond, &mutex.m_mutex, &abstime);
		}
		if (ret==0)
		{
			return true;
		}
		else
		{
			if (errno==EINTR)
			{
				THROW_EXCEPTION(InterruptedException,"pthread_cond_timedwait failed",errno);
			}
			else if (errno==ETIMEDOUT && timeout >= 0)
			{
				return false;
			}
		}
		return true;
#endif
	}
Exemplo n.º 4
0
void
InputEvents::DoQueuedEvents()
{
  assert(InMainThread());

  int GCE_Queue_copy[MAX_GCE_QUEUE];
  int i;

  // copy the queue first, blocking
  mutexEventQueue.Lock();
  std::copy(GCE_Queue, GCE_Queue + MAX_GCE_QUEUE, GCE_Queue_copy);
  std::fill(GCE_Queue, GCE_Queue + MAX_GCE_QUEUE, -1);
  mutexEventQueue.Unlock();

  // process each item in the queue
  for (i = 0; i < MAX_GCE_QUEUE; i++) {
    if (GCE_Queue_copy[i] != -1) {
      processGlideComputer_real(GCE_Queue_copy[i]);
    }
  }
  for (i = 0; i < MAX_NMEA_QUEUE; i++) {
    if (NMEA_Queue[i] != -1)
      processNmea_real(NMEA_Queue[i]);
  }
}
Exemplo n.º 5
0
// ******************************************************************
// * CxbxRtlAllocDebug - Debug track RTL alloc
// ******************************************************************
void *CxbxRtlAllocDebug(HANDLE  Heap,
                        DWORD   Flags,
                        SIZE_T  Bytes,
                        char   *pFile,
                        int     Line)
{
    void *pRetMem = NULL;
    g_MemoryMutex.Lock();

    void *pMem = NtDll::RtlAllocateHeap(Heap, Flags, Bytes + 2 * sizeof(MEMORY_GUARD));
    if(!pMem)
    {
        printf("CxbxRtlAllocDebug: Allocation failed\n"
               "    Heap  : 0x%.08X\n"
               "    Flags : 0x%.08X\n"
               "    Bytes : %d\n"
               "    File  : %s\n"
               "    Line  : %d\n",
               Heap, Flags, Bytes, pFile, Line);
    }
    else
    {
        CXBX_MEMORY_BLOCK *pBlock = InsertMemoryBlock(pMem,
                                                      Bytes,
                                                      pFile,
                                                      Line,
                                                      CXBX_ALLOC_RTL);
        pRetMem = pBlock->pMem;
    }

    g_MemoryMutex.Unlock();

    return pRetMem;
}
Exemplo n.º 6
0
// ******************************************************************
// * CxbxCallocDebug - Debug track calloc
// ******************************************************************
void *CxbxCallocDebug(size_t  NbrElements,
                      size_t  ElementSize,
                      char   *pFile,
                      int     Line)
{
    void *pRetMem = NULL;
    g_MemoryMutex.Lock();

    void *pMem = calloc(NbrElements * ElementSize + 2 * sizeof(MEMORY_GUARD), 1);
    if(!pMem)
    {
        printf("CxbxCallocDebug: Allocation failed\n"
               "    NbrElements: %d\n"
               "    ElementSize: %d\n"
               "    File       : %s\n"
               "    Line       : %d\n",
               NbrElements, ElementSize, pFile, Line);
    }
    else
    {
        CXBX_MEMORY_BLOCK *pBlock = InsertMemoryBlock(pMem,
                                                      NbrElements * ElementSize,
                                                      pFile,
                                                      Line,
                                                      CXBX_ALLOC_NORMAL);
        pRetMem = pBlock->pMem;
    }

    g_MemoryMutex.Unlock();

    return pRetMem;
}
Exemplo n.º 7
0
    static Cursor& getInstance() {
        sLock.Lock();
        if( sInstance==0 )	sInstance = new Cursor;
        sLock.UnLock();

        return *sInstance;
    }
Exemplo n.º 8
0
// Function that generates clients to receive messages.
void ClientThread(void* args)
{
    MessageClient client;
    std::string message;
    unsigned int count = 0;
    unsigned int total = 0;
    if(client.Initialize(gServerID, MessageClient::AnyID, MappedMessageBox::DefaultSize, false))
    {
        while(gQuitFlag == false)
        {
            // See if a message has been received by this
            // client process.  A better method would be to 
            // use a callback so you don't have to poll.
            if(client.ReadMessage(message))
            {
                ++total;
                // Only print to the screen every N messages, failure to do 
                // so will skew performance results because it takes time to
                // write to the console window.
                if(++count == 100)
                {
                    count = 0;
                    gPrintMutex.Lock();
                    // Display the percent of messages generated that we've been
                    // able to receive.
                    cout << client.GetID() << " Received " << total*100.0/gTotalMessages << " Percent" << endl;
                    gPrintMutex.Unlock();
                }
            }
            SleepMs(1);
        }
    }
}
Exemplo n.º 9
0
__declspec(dllexport) void __stdcall WH_KEYBOARD_LL_Block(unsigned long virtualkeycode)
{
	mWH_KEYBOARD_LL_Keys.Lock(true);
		sWH_KEYBOARD_LL_Keys.remove(virtualkeycode);
		sWH_KEYBOARD_LL_Keys.push_back(virtualkeycode);
	mWH_KEYBOARD_LL_Keys.Unlock();
}
Exemplo n.º 10
0
UINT startSendInfo(LPVOID lpParam)
{
	mx.Lock();
	sender.SendInfo();
	return 0;
	mx.Unlock();
}
Exemplo n.º 11
0
bool
System::Startup(
	int*, char**)
{
	Mutex mutex;
	mutex.Lock();
	{
		System::m_StartupTime = Process::GetTimeInSeconds();
		Process::Startup();
		ThreadEngine::Startup();
		LogEngine::Startup();
		ResourceEngine::Startup();
		Symbol::CreateRegistry();
		MetaClass::CreateRegistry();
		vd::f64 dt = Process::GetTimeInSeconds();

		vdLogGlobalInfo("Void Framework v%d.%d.%d - %s: startup time '%f' sec", 
			VD_VERSION_MAJOR, 
			VD_VERSION_MINOR, 
			VD_VERSION_PATCH, 
			VD_BUILD_INFO,
			dt - m_StartupTime);
	}
	mutex.Unlock();
	return true;
}
 int MidiInstrumentMapper::AddMap(String MapName) throw (Exception) {
     int ID;
     midiMapsMutex.Lock();
     if (midiMaps.empty()) ID = 0;
     else {
         // get the highest existing map ID
         uint lastIndex = (--(midiMaps.end()))->first;
         // check if we reached the index limit
         if (lastIndex + 1 < lastIndex) {
             // search for an unoccupied map ID starting from 0
             for (uint i = 0; i < lastIndex; i++) {
                 if (midiMaps.find(i) != midiMaps.end()) continue;
                 // we found an unused ID, so insert the new map there
                 ID = i;
                 goto __create_map;
             }
             throw Exception("Internal error: could not find unoccupied MIDI instrument map ID.");
         }
         ID = lastIndex + 1;
     }
     __create_map:
     midiMaps[ID].name = MapName;
     
     fireMidiInstrumentMapCountChanged(Maps().size());
     // If there were no maps until now we must set a default map.
     if (midiMaps.size() == 1) SetDefaultMap(ID);
     midiMapsMutex.Unlock();
     
     return ID;
 }
Exemplo n.º 13
0
void
ManagedFileListWidget::OnDownloadComplete(Path path_relative,
                                          bool success)
{
  const auto name = path_relative.GetBase();
  if (name == nullptr)
    return;

  const WideToUTF8Converter name2(name.c_str());
  if (!name2.IsValid())
    return;

  const std::string name3(name2);

  mutex.Lock();

  downloads.erase(name3);

  if (StringIsEqual(name2, "repository")) {
    repository_failed = !success;
    if (success)
      repository_modified = true;
  } else if (!success)
    failures.insert(name3);

  mutex.Unlock();

  SendNotification();
}
 void MidiInstrumentMapper::RemoveAllMaps() {
     midiMapsMutex.Lock();
     midiMaps.clear();
     SetDefaultMap(-1);
     fireMidiInstrumentMapCountChanged(Maps().size());
     midiMapsMutex.Unlock();
 }
 void MidiInstrumentMapper::SetDefaultMap(int MapId) {
     midiMapsMutex.Lock();
     DefaultMap = MapId;
     midiMapsMutex.Unlock();
     
     if (MapId != -1) fireMidiInstrumentMapInfoChanged(MapId);
 }
Exemplo n.º 16
0
void
ManagedFileListWidget::OnDownloadComplete(const TCHAR *path_relative,
                                          bool success)
{
  const TCHAR *name = BaseName(path_relative);
  if (name == NULL)
    return;

  WideToACPConverter name2(name);
  if (!name2.IsValid())
    return;

  const std::string name3(name2);

  mutex.Lock();

  downloads.erase(name3);

  if (StringIsEqual(name2, "repository")) {
    repository_failed = !success;
    if (success)
      repository_modified = true;
  } else if (!success)
    failures.insert(name3);

  mutex.Unlock();

  SendNotification();
}
Exemplo n.º 17
0
void devRestart() {
  if (is_simulator())
    return;

  /*
#ifdef WINDOWSPC
  static bool first = true;
  if (!first) {
    NMEAParser::Reset();
    return;
  }
  first = false;
#endif
  */
  StartupStore(TEXT("RestartCommPorts\n"));

  mutexComm.Lock();

  devShutdown();
  NMEAParser::Reset();

  devInit(TEXT(""));

  mutexComm.Unlock();
}
Exemplo n.º 18
0
/**
 * Fills the SimStepData from a Transfer thread with the first simulation result from the SRD queue
 * This method won't filter the data, all existing and available parameter, algebraic and states will be saved.
 * parameter: pointer from type SimStepData, it points on a data struct in a Transfer thread
 */
bool getResultData(SimStepData* p_SimResDataForw_from_Transfer) {
  bool retValue = true;

  /*
   * This part is necessary for the producer &consumer problem with districted buffer
   * An entity which want to use the array must pas this part
   */
  ghSemaphore_NumberUsedSlots.Wait();
  ssdMutex.Lock();

  /********************************************************************
   * Entity has pas the synchronization station and can work on the SSD buffer
   */
  if ((*pp_srdfArray_FirstQueueElement)->forTimeStep != -1) {
    popSRDF(p_SimResDataForw_from_Transfer);
  } else{
    //cout << "no chance ;) for time: " << (*pp_srdfArray_FirstQueueElement)->forTimeStep << endl; fflush(stdout);
  }


  // Release the mutex
  ssdMutex.Unlock();
  ghSemaphore_NumberFreeSlots.Post();

  return retValue;
}
Exemplo n.º 19
0
int main() {
  pthread_t thr;

  int var = 0;  // Going to be shared 

  printf("main(): Before pthread_create;\n  var=%d\n", var);
  if (pthread_create(&thr, NULL, thrp, &var) != 0) {
    fprintf(stderr, "pthread_create failed\n");
    return 1;
  }

  printf("starting main() loop...\n");
  for (int i = 0;
       i < ITERATIONS_PER_THREAD / ITERATIONS_PER_BURST;
       i++) {
    mu.Lock();
    for (int j = 0; j < ITERATIONS_PER_BURST; j++) {
      var++;
    }
    mu.Unlock();
  }
  printf("main() loop finished; intermediate result = %d\n", var);

  if (pthread_join(thr, NULL) != 0) {
    fprintf(stderr, "pthread_join failed\n");
    return 1;
  }
  printf("\nResults:\n  var      = %d\n  expected = %d\n",
         var, 2*ITERATIONS_PER_THREAD);

  return 0;
}
Exemplo n.º 20
0
      /**
       * \brief Test mutex.
       */
      void testMutex()
      {
        Mutex mutex;

        CPPUNIT_ASSERT(mutex.Lock());
        CPPUNIT_ASSERT(mutex.Unlock());
      }
Exemplo n.º 21
0
// TestMutex
//------------------------------------------------------------------------------
void TestMutex::TestMultiLockUnlock() const
{
    Mutex m;
    m.Lock();
    m.Lock();
    m.Unlock();
    m.Unlock();
}
Exemplo n.º 22
0
/**
 * Reads the SimStepData from a Calculation thread and adds it to the intern SSD buffer and the SRDF buffer.
 * parameter: pointer from type SimStepData, it points on a data struct in a Calculation thread
 */
bool setResultData(SimStepData* p_SimStepData_from_Calculation) {
  bool retValue = true;

  /*
   * This part is necessary for the producer &consumer problem with districted buffer
   * The any entity which want to use the array must pas this part
   */
  // Try to enter the ghSemaphore_NumberFreeSlots gate.
  ghSemaphore_NumberFreeSlots.Wait();

  ssdMutex.Lock();
  /********************************************************************
   * Entity has pas the synchronization sektion and can work on the SSD buffer
   * Restrictions: if the simulation has been reseted the first time value must be VALID_TIME_AFTER_RESET
   * otherwise the result won't be added to the system
   */

  //block used by normal running simulation
  if(!simulationReset && !simulationChangetime){
    addDataToSSD(p_SimStepData_from_Calculation);
    //cout << "add time: " << p_SimStepData_from_Calculation->forTimeStep   << endl; fflush(stdout);
  }else{//block used once after simulation has been reseted or more if the next time to add into the ssd is not VALID_TIME_AFTER_RESET
    if(simulationReset){
      if(p_SimStepData_from_Calculation->forTimeStep == VALID_TIME_AFTER_RESET || p_SimStepData_from_Calculation->forTimeStep == 0){
          addDataToSSD(p_SimStepData_from_Calculation);
          //cout << "add after reset time: " << p_SimStepData_from_Calculation->forTimeStep   << endl; fflush(stdout);
          simulationReset = false;
      }
      else{
        //cout << "no chance for reset ;) time: " << p_SimStepData_from_Calculation->forTimeStep << endl; fflush(stdout);
      }
    } else{
      if(simulationChangetime){

        if(compareDouble(p_SimStepData_from_Calculation->forTimeStep, VALID_TIME_AFTER_CHANGETIME)){
          //cout << "add after change time: " << p_SimStepData_from_Calculation->forTimeStep   << endl; fflush(stdout);
            addDataToSSD(p_SimStepData_from_Calculation);
            simulationChangetime = false;
        } else{
          //cout << "no chance for change ;) time: " << p_SimStepData_from_Calculation->forTimeStep << endl; fflush(stdout);
        }
      }
    }
  }

  //Work on SSD and SRDF buffer ended **********************************

  // Release the mutex
  if (!ssdMutex.Unlock()) {
    //printf("ReleaseMutex ssdMutex error: %d\n", GetLastError());
    return false;
  }
  //if(debugResultManager) { cout << "set released mutex" << endl; fflush(stdout); }
  // Release the semaphore ghSemaphore_NumberUsedSlots
  ghSemaphore_NumberUsedSlots.Post();

  return retValue;
}
Exemplo n.º 23
0
void CondVar::Wait(Mutex& externalMutex)
{
#ifdef WIN32
	SignalObjectAndWait(externalMutex.mutex,condVarEvent,INFINITE,FALSE);
	externalMutex.Lock();
#else
	pthread_cond_wait(&condVar,&externalMutex.mutex);
#endif
}
Exemplo n.º 24
0
TEST(Mutex, ManualLock) {
  Mutex* mutex = new Mutex;
  EXPECT_FALSE(mutex->isLocked());
  ASSERT_TRUE(mutex->Lock());
  EXPECT_TRUE(mutex->isLocked());
  ASSERT_TRUE(mutex->Unlock());
  EXPECT_FALSE(mutex->isLocked());
  delete mutex;
};
 void MidiInstrumentMapper::RemoveMap(int Map) {
     midiMapsMutex.Lock();
     midiMaps.erase(Map);
     if(Map == GetDefaultMap()) {
         SetDefaultMap(midiMaps.empty() ? -1 : (*(midiMaps.begin())).first);
     }
     fireMidiInstrumentMapCountChanged(Maps().size());
     midiMapsMutex.Unlock();
 }
Exemplo n.º 26
0
 virtual void DataReceived(const void *data, size_t length) {
   mutex.Lock();
   auto range = buffer.Write();
   if (range.length < length)
     length = range.length;
   memcpy(range.data, data, length);
   buffer.Append(length);
   mutex.Unlock();
   SendNotification();
 }
Exemplo n.º 27
0
void Kore::waitForThreadStopThenFree(Thread *sr) {
	mutex.Lock();
	IOS_Thread *t = (IOS_Thread*)sr;
Again:;
	int ret = pthread_join(t->pthread, NULL);
	if (ret != 0) goto Again;
	mutex.Unlock();
	int ti = static_cast<int>(((upint)t - (upint)&tt[0]) / sizeof(IOS_Thread));
	//ia.DeallocateIndex(ti);
}
 void MidiInstrumentMapper::RenameMap(int Map, String NewName) throw (Exception) {
     midiMapsMutex.Lock();
     std::map<int,MidiInstrumentMap>::iterator iterMap = midiMaps.find(Map);
     if (iterMap == midiMaps.end()) {
         midiMapsMutex.Unlock();
         throw Exception("There is no MIDI instrument map " + ToString(Map));
     }
     iterMap->second.name = NewName;
     midiMapsMutex.Unlock();
     fireMidiInstrumentMapInfoChanged(Map);
 }
Exemplo n.º 29
0
void devWriteNMEAString(PDeviceDescriptor_t d, const TCHAR *text)
{
  TCHAR tmp[512];

  devFormatNMEAString(tmp, 512, text);

  mutexComm.Lock();
  if (d->Com)
    d->Com->WriteString(tmp);
  mutexComm.Unlock();
}
 std::vector<int> MidiInstrumentMapper::Maps() {
     std::vector<int> result;
     midiMapsMutex.Lock();
     for (std::map<int,MidiInstrumentMap>::iterator iterMap = midiMaps.begin();
          iterMap != midiMaps.end(); iterMap++)
     {
         result.push_back(iterMap->first);
     }
     midiMapsMutex.Unlock();
     return result;
 }