I am using a multithreaded C ++ program for the Linux platform where I need functionality similar to WaitForMultipleObjects ().
When searching for a solution, I noticed that there are articles that describe how to implement WaitForMultipleObjects () functions on Linux with examples, but these examples do not satisfy the scenario that I have to support.
The scenario in my case is pretty simple. I have a daemon process in which the main thread provides a method / callback to the outside world, for example in a DLL. The dll code is not under my control. The same main thread creates a new thread "Thread 1". In thread 1, an infinite loop must be executed in which it will wait for the shutdown event (shutdown of the daemon), or it will wait until the event available to the data is transmitted through the open method / callback mentioned above.
In short, the thread will wait for the shutdown event and the available event if, in case the shutdown event is signaled that the wait will satisfy, and the cycle will be broken or if an event with data is transmitted, then the wait will satisfy, and the thread will be busy business processing.
In the windows, this seems very straightforward. Below is the pseudo-visible MS Windows code for my script.
//**Main thread** //Load the DLL LoadLibrary("some DLL") //Create a new thread hThread1 = __beginthreadex(..., &ThreadProc, ...) //callback in main thread (mentioned in above description) which would be called by the DLL void Callbackfunc(data) { qdata.push(data); SetEvent(s_hDataAvailableEvent); } void OnShutdown() { SetEvent(g_hShutdownEvent); WaitforSingleObject(hThread1,..., INFINITE); //Cleanup here } //**Thread 1** unsigned int WINAPI ThreadProc(void *pObject) { while (true) { HANDLE hEvents[2]; hEvents[0] = g_hShutdownEvent; hEvents[1] = s_hDataAvailableEvent; //3rd parameter is set to FALSE that means the wait should satisfy if state of any one of the objects is signaled. dwEvent = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE); switch (dwEvent) { case WAIT_OBJECT_0 + 0: // Shutdown event is set, break the loop return 0; case WAIT_OBJECT_0 + 1: //do business processing here break; default: // error handling } } }
I want to implement the same for Linux. According to my understanding, when it comes to Linux, it has a completely different mechanism where we need to register for signals. If the completion signal is reached, the process finds out that it is about to stop, but before that the process must wait until the working thread is gracefully turned off.