views:

205

answers:

3

Hello all,

When running a thread in Android/Java:

public void run()
{
   while (running)
   {
      if (moreTasksToExec())
      {
         task = getNextTask()
         task.exec();
      }
   }
}

Is it OK to let it run and not using a semaphore to block while no work needs to be executed?

I am only using one thread, so I need no inter-thread synchronization.

+2  A: 

Two threads could get the same next task and try to run the same task at the same time. So I would think so.

Ólafur Waage
Perhaps I was a bit unclear. I will only use one thread which I queue my work in. I.e. there is no synchronization problems between two threads.
Henrik
Semaphores are used to restrict multiple threads access to the same code. So if there is only one thread running this at any time, then you should be ok.
Ólafur Waage
OK, I was thinking the semaphore and the thread would block and not hog the CPU and then I would release it after queueing a task to exec it. So a thread with a loop without any kind of "blocking" or sleep does not hog the CPU?
Henrik
A looping thread with no blocking/sleep WILL hog CPU. It seems like your question was not entirely clear about what you were asking and why. Semaphore are used for protecting access to shared data, not for keeping a thread from hogging CPU.
unholysampler
What I have seen done in some cases (i dont know yours well though) is in the main thread, check if there are tasks to be run, if there are, spawn a thread to work them untill they are done.
Ólafur Waage
A: 

You should at least put a sleep in there so you don't hog the cpu.

CaseyB
+1  A: 

You might be better off with:

public void run()
{
  while (true) {
    task = getNextTask();  // blocks until task available
    if (task == null)
      break;
  }
}

getNextTask() returns null if it's time to stop running. Alternatively, check for "task == STOP_TASK" and have whatever code currently sets running=false post STOP_TASK onto the task queue.

Another approach is to use Thread.interrupt() to wake up a sleeper, but that always feels sleazy somehow. :-)

If you do retain the above approach, make sure "running" is declared volatile if it can be modified by another thread.

fadden