Nuno Santos
Nuno Santos

Reputation: 41

Multithreading doing something while on wait

I've a program that basically has a matrix of cells(shared memory) and cars(observable threads). Before each movement each car asks for access to the next cell, and if the next is blocked it enters a synchronized block which calls wait(), and the thread goes to sleep. I was wondering if there was any way I could make the car do something while it's on wait(), and then when he gets notified he can keep on doing what he was doing before the wait.

Upvotes: 0

Views: 89

Answers (2)

donfede
donfede

Reputation: 734

I've done something similar to what you describe, using Handlers for 2-way thread communication.

  • child/worker/'car' thread does work, goes to sleep for a set period (~100ms), and when waking up checks a thread class member variable for state changes.

  • parent thread will send Handler messages to the worker thread, and the worker thread receives the commands and sets member variable in worker thread class, to be detected next time the worker exits sleep.

Below are the links I've been reviewing to grasp how to use Handlers and communicate between threads effectively:

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

You'll have to redesign: don't model cars with threads. Have a thread pool perform any needed tasks and have an asynchronous model with callback functions guide the behavior of cars. If a cell is blocked, the state of the car simply doesn't change and the thread pool can do something else. When the cell is freed, fire the appropriate callback, which will submit the update task to the pool.

Upvotes: 1

Related Questions