Replacement for Windows specific HANDLE, Event Creation and Sync API in case of Linux

Viewed 292

I have a following set of codes specific to Windows,

    //1: Declaring HANDLE
    HANDLE *m_handle;
    
   //2: Creating HANDLE instance   
   int m_Count = 4;
   m_handle = new HANDLE[m_Count];

   //3: Creating Events
   for (int i = 0; i < m_Count ; i++)
    {
        m_handle [i] = CreateEvent(NULL, FALSE, FALSE, NULL);
    }

   //4: Synchronous API
   DWORD dwEvent = WaitForMultipleObjects(m_Count, m_handle, TRUE, 30000);

   //5: Closing the HANDLE
   for (int i = 0; i < m_Count; i++)
    {
        CloseHandle(m_handle[i]);
    }

How to write the same set of code in case of Linux?

1 Answers

The replacement for CreateEvent is eventfd, you probably want EFD_CLOEXEC and EFD_NONBLOCK flags. Don’t use the semaphore flag unless you know what you’re doing.

The replacement for WaitForMultipleObjects is poll, specify the POLLIN flag in the requested events. Just keep in mind the event is not being reset by poll, it will stay signalled. Read 8 bytes from the eventfd handle to reset. The functionality is identical to manual-reset events on Windows.

To signal an event, call write on the eventfd handle, passing the address of a local uint64_t variable with value 1.

To destroy events once you no longer need them, just call close.

Update: I’ve just noticed you’re passing bWaitAll=TRUE to WaitForMultipleObjects.

Unfortunately, Linux poll can’t quite do that. It returns when timeout is expired, or when at least 1 handle becomes signaled, whichever happens first.

Still, the workaround is not too hard. You can emulate bWaitAll by calling poll multiple times in a loop until all of the events are signaled. No need to rebuild the array of handles, you can set file handle to a negative value for the events which became signaled after poll returned. Note that multiple of them may become signaled at once, poll return value tells how many of them did. Also don't forget to decrease the timeout value.

Related