Alex Rivera | Logout

Linux Threads suspend/resume

Asked 2012-07-13T10:05:12.267
16

I'm writing a code in which I have two threads running in parallel.

1st is the main thread which started the 2nd thread. 2nd thread is just a simple thread executing empty while loop.

Now I want to pause / suspend the execution of 2nd thread by 1st thread who created it. And after some time I want to resume the execution of 2nd thread (by issuing some command or function) from where it was paused / suspended.

Edit
Report

1 Answer

1

For implementing the pause on a thread, you need to make it wait for some event to happen. Waiting on a spin-lock mutex is CPU cycle wasting. IMHO, this method should not be followed as the CPU cycles could have been used up by other processes/threads. Wait on a non-blocking descriptor (pipe, socket or some other). Example code for using pipes for inter-thread communication can be seen here Above solution is useful, if your second thread has more information from multiple sources than just the pause and resume signals. A top-level select/poll/epoll can be used on non-blocking descriptors. You can specify the wait time for select/poll/epoll system calls, and only that much micro-seconds worth of CPU cycles will be wasted. I mention this solution with forward-thinking that your second thread will have more things or events to handle than just getting paused and resumed. Sorry if it is more detailed than what you asked.

Another simpler approach can be to have a shared boolean variable between these threads. Main thread is the writer of the variable, 0 - signifies stop. 1 - signifies resume Second thread only reads the value of the variable. To implement '0' state, use usleep for sime micro-seconds then again check the value. Assuming, few micro-seconds delay is acceptable in your design. To implement '1' - check the value of the variable after doing certain number of operations. Otherwise, you can also implement a signal for moving from '1' to '0' state.

answered 2012-07-14T19:05:21.523

Your Answer