I am not able to understand the PulseEvent or race condition. But to avoid it I am trying to SetEvent instead, and ResetEvent every time before WaitForMultipleObjectsEx.
This is my flow:
Thread One - Uses CreateEvent to create an auto reseting event, I then spawn and tell Thread TWO about it.
Thread One - Tell thread TWO to run.
Thread TWO will do ResetEvent on event and then immediately start WaitForMultipleObjectsEx on the event and some other stuff for file watching. If WaitForMultipleObjectsEx returns, and it is not due to the event, then restart the loop immediately. If WaitForMultipleObjectsEx returns, due to event going to signaled, then do not restart loop.
So now imagine this case please:
Thread TWO - loop is running
Thread One - needs to add a path, so it does (1) SetEvent, and then (2) sends another message to thread 2 to add a path, and then (3) sends message to thread 2 to restart loop.
The messages of add path and restart loop will not come in to Thread TWO unless I stop the loop in TWO, which is done by the SetEvent. Thread TWO will see it was stoped due to the event, and so it wont restart the loop. So it will now get the message to add path, so it will add path, then restart loop.
Thread One - needs to stop the thread, so it does (1) SetEvent and then (2) waits for message thread 2, when it gets that message it will terminate the thread.
Will this avoid race condition?
Thank you
Suppose the loop needs to be interrupted twice in succession. You're imagining a sequence of events something like this, on thread ONE and thread TWO:
Thread ONE realizes that the first interruption is complete.
Thread ONE sends a message telling TWO to restart the wait loop.
Thread TWO reads the message "restart the wait loop".
Thread TWO resets the event.
Thread TWO starts waiting.
Thread ONE now realizes that another interruption is needed.
Thread ONE sets the event to ask for another interruption.
Thread ONE sends message related to the second interruption.
Thread TWO stops the loop, receives the message about the second interruption.
But since you don't have any control over the timing between the two threads, it might instead happen like this:
Thread ONE realizes that the first interruption is complete.
Thread ONE sends a message telling TWO to restart the wait loop.
Thread ONE now realizes that another interruption is needed.
Thread ONE sets the event to ask for another interruption.
Thread TWO reads the message "restart the wait loop".
Thread TWO resets the event.
Thread TWO starts waiting.
Thread ONE sends a message about the second interruption, but TWO isn't listening!
Even if the message passing mechanism is synchronous, so that ONE won't continue until TWO has read the message, it could happen this way:
Thread ONE realizes that the first interruption is complete.
Thread ONE sends a message telling TWO to restart the wait loop.
Thread TWO reads the message "restart the wait loop", but is then swapped out.
Thread ONE now realizes that another interruption is needed.
Thread ONE sets the event to ask for another interruption.
Thread TWO resets the event.
Thread TWO starts waiting.
Thread ONE sends a message about the second interruption, but TWO isn't listening!
(Obviously, a similar thing can happen if you use PulseEvent.)
One quick solution would be to use a second event for TWO to signal ONE at the appropriate point, i.e., after resetting the main event but before waiting on it, but that seems somewhat inelegant and also doesn't generalize very well. If you can guarantee that there will never be two interruptions in close-enough succession, you might simply choose to ignore the race condition, but note that it is difficult to reason about this because there is no theoretical limit to how long it might take for thread TWO to resume running after being swapped out.
The various alternatives depend on how the messages are being passed between the threads and any other constraints. [If you can provide more information about your current implementation I'll update my answer accordingly.]
This is an overview of some of the more obvious options.
If the message-passing mechanism is synchronous (if thread ONE waits for thread TWO to receive the message before proceeding) then using a single auto-reset event should just work. Thread ONE won't set the event until after thread TWO has received the restart-loop message. If the event is already set when thread TWO starts waiting, that just means that there were two interruptions in immediate succession; TWO will never stall waiting for a message that isn't coming. [This potential stall is the only reason I can think of why you might not want to use an auto-reset event. If you have another concern, please edit your question to provide more details.]
If is OK for sending a message to be non-blocking, and you aren't already locked in to a particular solution, any of these options would probably be sensible:
User mode APCs (the QueueUserAPC function) provide a message-passing mechanism that automatically interrupts alertable waits.
You could implement a simple queue (protected by a critical section) which uses an event to indicate whether there is a message pending or not. In this case you can safely use a manual-reset event provided that you only manipulate it when you hold the same critical section that protects the queue.
You could use an auto-reset event in combination with any sort of thread-safe queue, provided only that the queue allows you to test for emptiness without blocking. The idea here is that thread ONE would always insert the message into the queue before setting the event, and if thread TWO sees that the event is set but it turns out that the queue is empty, the event is ignored. If efficiency is a concern, you might even be able to find a suitable lock-free queue implementation. (I don't recommend attempting that yourself.)
(All of those mechanisms could also be made synchronous by using a second event object.)
I wouldn't recommend the following approaches, but if you happen to already be using one of these for messaging this is how you can make it work:
If you're using named pipes for messaging, you could use asynchronous I/O in thread TWO. Thread TWO would use an auto-reset event internally, you specify the event handle when you issue the I/O call and Windows sets it when I/O arrives. From the point of view of thread ONE, there's only a single operation. From the point of view of thread TWO, if the event is set, a message is definitely available. (I believe this is somewhat similar to your original approach, you just have to issue the I/O call in advance rather than afterwards.)
If you're using a window queue for messaging, the MsgWaitForMultipleObjectsEx() function allows you to wait for a window message and other events simultaneously.
PS:
The other problem with PulseEvent, the one mentioned in the documentation, is that this can happen:
Thread TWO starts waiting.
Thread TWO is preempted by Windows and all user code on the thread stops running.
Thread ONE pulses the event.
Thread TWO is restarted by Windows, and the wait is resumed.
Thread ONE sends a message, but TWO isn't listening.
(Personally I'm a bit disappointed that the kernel doesn't deal with this situation; I would have thought that it would be possible for it to set a flag saying that the wait shouldn't be resumed. But I can only assume that there is a good reason why this is impractical.)
The Auto-Reset Events
Would you please try to change the flow so there is just SetEvent and WaitForMultipleObjectsEx with auto-reset events? You may create more events if you need. For example, each thread will have its own pair of events: one to get notifications and another to report about its state changes - you define the scheme that best suits your needs.
Since there will be auto-reset events, there would be neither ResetEvent nor PulseEvent.
If you will be able to change the logic of the algorithm flow this way - the program will become clear, reliable, and straightforward.
I advise this because this is how our applications work since the times of Windows NT 3.51 – we manage to do everything we need with just SetEvent and WaitForMultipleObjects (without the Ex suffix).
As for the PulseEvent, as you know, it is very unreliable, even though it exists from the very first version of Windows NT - 3.1 - maybe it was reliable then, but not now.
To create the auto-reset events, use the bManualReset argument of the CreateEvent API function (if this parameter is TRUE, the function creates a manual-reset event object, which requires the use of the ResetEvent function to set the event state to non-signaled -- this is not what you need). If this parameter is FALSE, the function creates an auto-reset event object. The system will automatically reset the event state to non-signaled after a single waiting thread has been released, i.e., after WaitForMultipleObjects or WaitForSingleObject or other wait functions that explicitly wait for this event to become signaled.
These auto-reset events are very reliable and easy to use.
Let me make a few additional notes on the PulseEvent. Even Microsoft has admitted that PulseEvent is unreliable and should not be used -- see https://msdn.microsoft.com/en-us/library/windows/desktop/ms684914(v=vs.85).aspx -- because only those threads will be notified that are in the "wait" state when PulseEvent is called. If they are in any other state, they will not be notified, and you may never know for sure what the thread state is, and, even if you are responsible for the program flow, the state can be changed by the operating system contrary to your program logic. A thread waiting on a synchronization object can be momentarily removed from the wait state by a kernel-mode Asynchronous Procedure Call (APC) and returned to the wait state after the APC is complete. If the call to PulseEvent occurs during the time when the thread has been removed from the wait state, the thread will not be released because PulseEvent releases only those threads that are waiting at the moment it is called.
You can find out more about the kernel-mode APC at the following links:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681951(v=vs.85).aspx
http://www.drdobbs.com/inside-nts-asynchronous-procedure-call/184416590
http://www.osronline.com/article.cfm?id=75
The Manual-Reset Events
The Manual-Reset events are not that bad. :-) You can reliably use them when you need to notify multiple instances of a global state change that occurs only once, for example, application exit. The auto-reset events can only be used to notify one thread (because if more threads are waiting simultaneously for an auto-reset event and you set the event, one random thread will exist and will reset the event, but the behavior of the remaining threads that also wait for the event, will be undefined). From the Microsoft documentation, we may assume that one and only one thread will exit while others would definitely not exit, but this is not very explicitly articulated in the documentation. Anyway, we must take the following quote into consideration: "Do not assume a first-in, first-out (FIFO) order. External events such as kernel-mode APCs can change the wait order" Source - https://msdn.microsoft.com/en-us/library/windows/desktop/ms682655(v=vs.85).aspx
So, when you need to notify all the threads quickly – just set the manual-reset event to the signaled state, rather than signaling each auto-reset event for each thread. Once you have signaled the manual-reset event, do not call ResetEvent since then. The drawback of this solution is that the threads need to have an additional event handle passed in the array of their WaitForMultipleObjects. The array size is limited, although, to MAXIMUM_WAIT_OBJECTS, which is 64, we never reached close to this limit in practice.
You can get more ideas about auto-reset events and manual reset events from https://www.codeproject.com/Articles/39040/Auto-and-Manual-Reset-Events-Revisited
I am facing a problem about the message queue:
I have used mq_timedreceive() to get message queue in abs_timeout time.
But this function is affected by system time (CLOCK_REALTIME). I mean that when system time change, the abs_timeout (absolute time) is not right any more.
To fix this problem, I realize that it should change to CLOCK_MONOTOIC clock.
But in linux, there is no way (I seached and found QNX support this mechanism).
Finally, I combine select() and mq_timereceive with NO_WAIT.
+ select(): using relative time so it's not affected by system time changing.
After timeout, I will get message queue with mq_timereceive(), of course absolute time = 0;
But my problem is:
If system have many thread that are waiting the same message queue (by using select()),
If a message is sent to message queue, all waiting thread are woken up and running. So it's wrong.
Maybe a thread (not first waiting thread) wake up first and get this message.
My expected is only first waiting thread should woken up and it will get message, and others still block.
Please help.
Looks like you have several questions in one:
Waiting on a message queue with a timeout that is not affected by clock adjustments. In Linux the following APIs support clock (CLOCK_REALTIME, CLOCK_MONOTONIC, etc.) selection: timerfd_create and timer_create. One way to integrate these with mq_timedreceive is to let timer_create fire a signal that interrupts mq_timedreceive.
Integrating waiting on a POSIX message queue with select. The most straight-forward way would be to use mq_notify to make it deliver a signal when a new message is available, thus making select call return -1 and errno set to EINTR.
Fair queuing, so that the first waiter gets the next message. With POSIX message queues it may be possible if the waiting threads are blocked in mq_receive. Otherwise the next available message is delivered to a thread that calls mq_receive first.
For message passing between threads of the same process another approach can be to have a pipe act as a queue of message pointers. That is, a producer thread creates a message and writes a pointer to it into the pipe (i.e. no need to serialize the entire message because the message recipient is in the same process and has access to the process address space). Any consumer thread can wait on the pipe using select and then read the pointers to messages. However, if multiple threads are waiting on the same pipe, they all get woken up but only one of the threads will read the message pointer off the pipe.
I use timerfd with TFD_NONBLOCK option.
This timer is added to epoll controller with only EPOLLIN event set.
If EPOLLIN occurs, read() is used on this timer.
In 99% cases everything works great. Execution stops on epoll_wait, then is continued after timer interval. However under heavy system load i received EAGAIN from read() a few times.
This looks like i receive EPOLLIN but then nothing is availible for reading.
I probably found an answer.
In my program I was using a few timers at once, some of them were modifying intervals of others. With little or no load epoll was executing single event at once. Under heavy load some events were queued and then executed in a loop. While processing the queue, if first event modified interval of next timer - it became 'not-ready'. But then loop proceeded to second timer, causing read() on not-ready-anymore timer.
Using timer_create, we deliver a real time signal to a thread which waits on select function.
This signal is caught and handled in the thread. Based on fact the select will be interrupted when a signal is caught, I have some logic implemented if select fails with error number EINTR.
This works fine most of the time, but occasionally I notice that select is not getting interrupted (or some how the code within EINTR case not getting executed).
What are possible reasons for this?
It can be that when the timer expiry signal is delivered you are not waiting in select, hence it does not return EINTR.
If you want to receive EINTR only when the thread is blocked in select, you may block that signal in the thread using pthread_sigmask and use pselect or epoll_pwait that would unblock that signal while waiting only. This way the rest of your code does not need to be concerned with handling EINTR.
If you have more than one thread in the process make sure you block that signal in all other threads, so that only one thread gets delivered that signal. See Signal Concepts for more details.
A more elegant option (IMO) is to avoid using timer_create and rather pass the delay to the next timer expiry as select time-out argument (this is what libevent does). But that requires you to maintain your own min-heap of timers.
This is a question regarding this answer: https://stackoverflow.com/a/14241095/2332808 (would comment it but newly created accounts apparently can't, sorry for the noise. Ressources on epollet/multithreading are hard to find...)
It suggests using epoll as the following:
epoll_ctl() to activate notifications (and reactivate if EPOLLONESHOT is used).
system input: read()/recv()/accept() in a loop until error EAGAIN.
epoll_wait() to receive notifications.
But, assuming there are multiple threads in epoll_wait() on the same epollfd, wouldn't this risk having another thread being woken up on the same fd if it receives more data before you're done reading (e.g. ending up with two threads processing the same fd)
Even if you turn things around and read() till EAGAIN, epoll_ctl() and then call read() again to check there's still nothing (to avoid the race where you'd receive something between the last read and the epoll_ctl())...
BUT there is still no guarantee that you wouldn't have actually received something after the epoll_ctl() and would have both the last read() check and another thread woken up working on the same fd again...
I guess having a lock per fd would be an acceptable solution, but is that the "approved" use of epoll in edge-triggering mode with multiple threads polling on the same epollfd ?
Yes, you still need to do proper locking to guard against those cases you describe - and using a lock per fd is the most sensible approach to do that.