Kill a thread after a certain amount of time in C - multithreading

Kill a child thread from the parent.
I'm modelling a customer as a thread in C. Now the customer has a property which specifies how long it can wait before it gets serviced.
If the time limit exceeds the wait time , than customer will go back from the service provider.
I know about pthread_cancel(), but how will I keep track of time for a thread.
How can I solve this problem with the thread printing if it was serviced or not before exiting.

Related

Python: Kill sleeping thread

I'm looking for ways to end a thread that is handling alarms.
Right now I make use of threads started via concurrent.futures.thread.ThreadPoolExecutor and I have one thread that simply waits to be given a datetime.datetime object through one queue.Queue, sleeps until the time specified in the datetime object is reached and then sends an alarm through another queue.
Since alarms will be scheduled repeatedly and the program is expected to run on a longer time scale, I don't want to make use of solutions like threading.Timer or asyncio.create_task, since they spawn new threads for each scheduled alarm. Is there a way to end/kill the sleeping thread prematurely or is there a better alternative for scheduling alarms than using ThreadPoolExecutor and a continuously sleeping thread?
Sadly I cannot find the question with the answer I ended up using anymore, but basically, I modified the timeout value to be the time I want to sleep. In combination with block=True, my script either gets another item from the queue or throws an Empty exception once the timeout is reached and I can continue as if my script just woke up from sleep.

How to monitor the health of a busy thread?

I am working on an application that has numerous threads with each thread performing a task that is different from the other. There is also a healthMonitor thread that monitors health of individual threads by sending heartbeat messages at regular intervals. Among these threads there is one thread T1 that posts messages to another thread T2 in response to which T2 does some file write operation.
On rare occasions, T1 sends a surge of messages for a prolonged duration to T2, because of which T2 becomes busy with file write operations. Sometimes these file-write operations can be time consuming taking up to 2 seconds to complete. In this situation, T2 does not respond to the heartbeat messages posted by the healthMonitor thread, causing the healthMonitor thread to kill the application.
T2 reads all incoming messages including those posted by T1 and the hearbeat messages posted by the healthMonitor thread, from the same messageQueue.
This issue occurs very rarely and cannot be re-produced at will thus making it difficult to debug.
I have concluded that during such situations where there are huge number of messages pending to be processed and with the processing time taking too long, the heartbeat messages remain unprocessed for too long. Because of this thread T2 does not respond to the healthMonitor thread on time.
My question is, what would be the proper way to handle this issue. I have few options in mind:
Limit the number of messages from thread T1. This approach would reduce the load from thread T2, but is this an elegant way to handle the situation?
Implement priority-based handling in the message queue: All heartbeat messages can be added to the head of the message queue instead of getting added to the tail so that it gets picked up first from the queue. Please note that we have our own implementation of message queue for inter-thread communication.
Or should I just focus on optimizing the file write operation in thread T2?

How linux kernel decide the next thread id

I have a question regarding linux kernel scheduling.
We know that, usually, linux maintains the current largest pid. If we want to start a new process, the kernel will use that largest id. So, if we kill and restart a new process, the process id are not sequential. Linux will use the largest id until it hits a limit.
But my question is how linux decides thread ID.
Say, process A and B are running. Process A crashes but process B is spawning new threads. Will process B just reuse that old tid belonging to process A, or, process B will also use the largest id as tid. Which case is more often? Do we have documents?
Thanks.
The kernel sets a maximum number of process/thread ids and simply recycles identifiers when the threads are garbage collected. So if process B spawns enough threads it will eventually reclaim thread ids from process A assuming it has been properly destroyed
Edit: Here are some links that can provide you with more specific answers
Difference between pid and tid
https://stackoverflow.com/a/8787888/5768168
"what is the value range of thread and process id?"
what is the value range of thread and process id?
"Linux PID recycling"
https://stackoverflow.com/a/11323428/5768168
"Process identifer"
https://en.wikipedia.org/wiki/Process_identifier#Unix-like
"The Linux kernel: Processes"
https://www.win.tue.nl/~aeb/linux/lk/lk-10.html
It sounds like you need to run your threads in with a PTHREAD_CREATE_JOINABLE attribute passed to pthread_create(), then have one reaper thread in your process dedicated to using pthread_join() or pthread_tryjoin() to wait for terminated threads. Rather than having an outside process trying to sort it out, have your process record the PID/TID pair after pthread_create() succeeds and have the reaper thread remove the pair when it detects the thread has terminated.
I typically combined that with a main thread that did nothing but spawn the thread-creation and reaper threads, then wait for a termination signal and terminate the thread-creator and reaper. The thread-creator stops immediately when signaled, the reaper stops when no more unterminated threads are running, the main thread terminates when both the thread-creator and reaper threads can be pthread_join()'d. Since the main thread's so simple it's unlikely to crash, which means most crashes in work threads simply deliver them to the reaper. If you want absolute certainty, your outside process should be the one to start your main process, then it can use wait() or it's siblings to monitor whether the main process has terminated (normally or by crashing).

Query Regarding Non Preemptive thread

I was reading about non preemptive threads and I found a slide from Princeton University and it shows the following diagram: (Source Link: http://www.cs.princeton.edu/courses/archive/fall11/cos318/lectures/L5_ThreadsImplementation.pdf)
From what I understood is that a thread to be executed is first put into a ready queue. When it pop's out of the queue it is in running state. If it wants to invoke another thread, it calls the yield function, which will store the current state of the thread and insert it in the tail of the queue. And the thread which is in the front of the queue will be executed.
What happens if The thread is blocked (i.e. it is waiting for some resource) ? I thought in non-preemptive thread it will wait for the resource and then carry on execution.
But from the below diagram it looks as though it goes into blocked state and then is put into the ready queue ? Why is that?
As said in the comments, non-preemptive means that another thread cannot interrupt (preempt) a running thread, not that the running thread won't yield when it has to wait for something.
When a thread is waiting for data from memory (for example), it's said to be in blocked state: its context is saved and another thread takes place in the computing resource (CPU core). When data is available in CPU's cache memory, then the first thread is said ready to resume its execution (and it will, as soon as it is the next to be executed and that the currently executed thread yields the computing resource).
This enables overlapping both data movements and threads execution, thus saving time by optimizing resource usage.

Few Questions about Threading, COM+ and STA apartments

I have a windows service which creates 10 threads + the one which creates the tasks list.
Each of these 11 threads enters STA by calling CoInitialize(nil).
Tasks list is created by one thread, other get the item, process it and free ....
a) Can the other thread use the object created by the other thread?
(Thats seems to work, but ..)
b) Can the other thread free the memory allocated by the other thread?
(Thats seems to not work...)
Should I somehow marshal the pointer between threads?
Or should I at least get the item, process it, but let it be freed be the "owner" of the thread which created it?
In my windows services I created the functionality which I can use to start/stop the services(suspand and resume the threads).
However I have a problem with the thread which actually collects the data and does it in the interval.
When the thread loads the items to process, then after it, it enters sleep state for 5 minutes.
How can i terminate such thread safely? How to abort sleep state?
Thanks in advance for your help!
You may have to marshall interfaces across threads. Here you can find a C++ example, and the same articles shows the three techniques you can use (oMarshalInterThreadInterfaceInStream/CoMarshalInterface/Global Interface Table(GIT)). More information about them you can find in MSDN.
To have a thread wait but being able to terminate it before the sleep ends, use WaitForSingleObject() with a proper timeout value and for example a Windows event to wait for. When the functions exit it will tell if it exited because the timeout elapsed or the event was set. To exit the wait function before the timeout is reached simnply set the event. Thereby you can choose if to enter another wait loop or exit.
To marshall an STA object pointer between STA threads use CoMarshallInterThreadInterfaceInStream, and CoGetInterfaceAndReleaseStream.
An STA thread MUST pump messages, as that is how STA threads use COM, using windows messages. I.e. you must call GetMessage/TranslateMessage/DispatchMessage. Probably your framework has a simple message pump function you could use to do this.
To abort your sleep state of 5 minutes, do multiple sleeps for shorter intervals, and check a "shouldquit" flag. Set the shouldquit flag in the Service Main.

Resources