Now i face a problem in my porting job, when i need to implement a thread class that will work in not only wince, symbian ,but also unix-like system, like iphone.
I own a suspend/resume interface to implement, anything is ok in wince/symbian except iphone, i use the posix pthread to finish my job, but i search the whole docsets for a resume/suspend-like interface. Things seem to be difficult, pthread in iphone own a pthread_create_suspended_np that can create a thread in a suspend mode. Now how can i resume or suspend a thread after the thread has run to its stuff in anytime.
BTW, i search Google for some help, it seems that someone else also have this problem .
Some guys suggest use the SIGHUP signal, but this will suspend the whole process, that’s absolutely not ok .
Many thanks if you guys can tell me some solutions for this problem.
It’s actually a bad idea to try and control threads externally. You never know what state they may be in when you suspend them. If they have a mutex lock on a resource that’s needed elsewhere, you can easily end up with a deadlock situation.
We had to create a “safe” suspend functionality without resorting to any non-portable pthread extensions a while ago and I’ll try to remember how we did it.
It consisted of a suspension mutex for each thread and a variable indicating that threads state. So the thread we wanted to suspend would have a loop (they mostly do) that went something like this:
and the code to suspend/resume the thread would be:
What the suspender would do is basically get a lock on the mutex and wait for the thread to enter suspended state (the writing to mystate was done only by the suspendee and did not have to be protected by another mutex). The
suspendfunction did not return until it was guaranteed that the suspendee would be stopped.Similarly, resuming the thread released the mutex so the suspendee could restart and then waited until it had restarted before returning.
This allowed suspension to take place but under the control of the thread being suspended. That was much safer since it could ensure it could only be suspended at safe points when it didn’t have any locks that could deadlock the application.