ark1974
ark1974

Reputation: 655

Transfer execution of a process from thread1 to thread2

Just a theoretical question (may not be even practical), asked just out of curiosity.

How can I transfer execution of a process LongComputation() from ThreadProcess1() to ThreadProcess2()without breaking the flow of the process? Is it possible? Here, ThreadProcess1() is time critical and LongComputation() is also important but not time-critical. Frankly, I fail to understand how to inject a running process to another secondary thread without breaking the process nor the current thread, with the available c++ concurrency toolkits

Here's a practical scenario : ThreadProcess1() is timebound, and finds that LongComputation() is taking more time than the set timout, it wants to transfer this process to another thread but wants to continue execution of the remaining code.

void LongComputation() {
    /* ... */
}

void ThreadProcess1() {
    /* start LongComputation()  

       tranfer the incomplete LongComputation() 

       to process2 for completing */
}

void ThreadProcess2() {

}

Upvotes: 0

Views: 122

Answers (1)

Pickle Rick
Pickle Rick

Reputation: 808

This is just off the top of my head, on mobile and can't test. Please rightfully tear me to shreds for posting it as an answer if I'm wrong. I'm fairly sure this could be done (hypothetically) by literally just transferring CPU state. Even from user mode, easy. Suspend t1 and grab its context via GetThreadContext (on Windows). Then do the same for t2 and use SetThreadContext to swap out the state. You will need a manager thread for this scenario, but it's purely hypothetical anyway as it would never be the best solution in the real world. All this would really do is slow things down by trigerring an interrupt to set another thread to resume code we were already executing. In reality, what you probably want is an event where you can signal t2 to do some work for t1 if it's taking too long.

Upvotes: 1

Related Questions