Jump to content

  • Log In with Google      Sign In   
  • Create Account

Task/Job Scheduler code review


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
6 replies to this topic

#1 Craig_jb   Members   -  Reputation: 181

Like
0Likes
Like

Posted 07 May 2012 - 12:04 AM

I've been working on a simple, cross-platform task/job scheduler, and I would like some help reviewing the code. Any feedback on general pitfalls or problems is appreciated!

I've posted the code on github, and below:
https://gist.github.com/2625036

/// This is not written to compile. I just copied everything into one file to make viewing easy
/// Here is a sample usage (task definitions and implementations omitted)
int main()
{
	TaskScheduler scheduler;
	MyTaskA taskA;
	MyTaskB taskB;
	BOOL running = true
	while (running)
	{
		scheduler.pushTask(&taskA);
		scheduler.pushTask(&taskB);
		scheduler.runUntilDone();
	}
}
#include "boost/thread.hpp"
class Task;
class TaskScheduler;
class WorkerThread;
//// HEADERS ////
/// Abstract interface for all tasks run by scheduler
class Task
{
public:
virtual ~Task() { }
/** Checks if all dependencies are met and the task can run
  *  @returns true if scheduler can run task, false otherwise
  */
virtual BOOL isReady() = 0;
/// User task code goes here
virtual void run() = 0;
/// Checks whether the task is marked complete
BOOL complete() { return m_complete; }
/** Sets the complete status of the task
  *  @param v Completetion status
  */
void setComplete(BOOL v) { m_complete = v; }
private:
/// Flag indicating task completion
BOOL m_complete;
};
/// Runs Tasks across multiple threads on multiple cores
class TaskScheduler
{
public:
/** Create scheduler with default number of worker threads.
  *  Default is 1 thread per 1 logical core (core or HT unit)
  */
TaskScheduler();
/** Create scheduler with specified number of worker threads
  *  @param n Number of worker threads (must be less than MAX_THREADS)
  */
TaskScheduler(U32 n);
/// Finishes all currently running tasks, then stops all worker threads.
~TaskScheduler();
/** Schedules a task for execection
  *  The task is assigned to the first idle work thread if there is one;
  *  otherwise, the task is put on the queue of a worker thread. Pushed tasks
  *  execute immediately.
  */
void pushTask(Task* t);
/// Blocks execution until all worker threads have completed there tasks
void runUntilDone();
/** Gets number of worker threads
  *  @return Number of worker threads
  */
U32 threadCount();
private:
U32 m_workerCount;
WorkerThread* m_workers[MAX_THREADS];
BOOL m_running;
U32 m_nextPushIndex;
friend class WorkerThread;
};
/** Implementation of a task-stealing worker thread for the TaskScheduler
*  WorkerThreads steal tasks from other WorkerThreads if they are out of tasks or
*  blocked by task dependencies. If a WorkerThread is truly out of tasks, it sleeps on a
*  condition variable until new tasks are available.
*/
class WorkerThread
{
public:
/** Creates a new worker thread--only called by a TaskScheduler
  *  The system thread is started and enters idle, waiting on a condition variable.
  *  @param scheduler Parent TaskScheduler
  */
WorkerThread(TaskScheduler* scheduler);
/// Deletes underlying system thread
~WorkerThread();
/** Adds a task to the local task pool
  *  This method is called by the TaskScheduler from the main thread and uses
  *  a spinlock to access task queue. Execution of the task can begin immediately after
  *  the lock mutex is released.
  *  @param t Task to add to queue
  */
void pushTask(Task* t);
/** Checks whether the worker thread is currently idling
  *  @return true if idling, false otherwise
  */
BOOL idling();
/** Blocks execution until the worker thread has completed all tasks in its queue
  *  and can no longer find tasks to steal
  */
void blockUntilDone();
/** Wakes the thread and joins execution
  *  TaskScheduler must have m_running = false or method will block indefinitely
  */
void stop();
private:
void thread_proc();
BOOL run();
void idle();
BOOL steal();
BOOL stealFromWorker(WorkerThread* wt);
TaskScheduler* m_scheduler;
boost::thread* m_internalThread;
boost::mutex m_workerMutex;
boost::condition_variable m_wakeUp;
boost::condition_variable m_done;
std::queue<Task*> m_tasks;
U32 m_taskCount;
BOOL m_idling;
BOOL m_dependencyBlocked;
};
//// HEADERS ////
//// IMPLEMENTATIONS ////
/// TASK SCHEDULER ///
TaskScheduler::TaskScheduler()
{
m_running = true;
// use number of 'logical cores' as default number of worker threads
// on CPUs with Hyperthreading, each core counts as 2
m_workerCount = boost::thread::hardware_concurrency();
for (U32 i = 0; i < m_workerCount; i++)
  m_workers[i] = new WorkerThread(this);
m_nextPushIndex = 0;
}
TaskScheduler::TaskScheduler(U32 n)
{
m_workerCount = n;
for (U32 i = 0; i < m_workerCount; i++)
  m_workers[i] = new WorkerThread(this);
m_nextPushIndex = 0;
}
TaskScheduler::~TaskScheduler()
{
m_running = false;
for (U32 i = 0; i < m_workerCount; i++)
  m_workers[i]->stop();
}
void TaskScheduler::pushTask(Task* t)
{
// try to find an idling worker thread
for (U32 i = 0; i < m_workerCount; i++)
{
  if (m_workers[i]->idling())
  {
   m_workers[i]->pushTask(t);
   return;
  }
}

// push it onto the next worker thread round-robin style
// if there isn't an idling thread
m_workers[m_nextPushIndex++]->pushTask(t);
if (m_nextPushIndex >= m_workerCount)
  m_nextPushIndex = 0;
}
void TaskScheduler::runUntilDone()
{
for (U32 i = 0; i < m_workerCount; i++)
  m_workers[i]->blockUntilDone();
}
U32 TaskScheduler::threadCount()
{
return m_workerCount;
}
/// TASK SCHEDULER ///
/// WORKER THREAD ///
WorkerThread::WorkerThread(TaskScheduler* scheduler)
{
m_scheduler = scheduler;
m_taskCount = 0;
m_idling = false;
m_dependencyBlocked = false;
// creates system thread
// thread_proc begins execution immediately
m_internalThread = new boost::thread(&WorkerThread::thread_proc, this);
}
WorkerThread::~WorkerThread()
{
delete m_internalThread;
}
void WorkerThread::pushTask(Task* t)
{
while (!m_workerMutex.try_lock());
m_tasks.push(t);
m_taskCount++;
m_idling = false;
m_workerMutex.unlock();

// wake up the thread if idling
m_wakeUp.notify_all();
}
BOOL WorkerThread::idling()
{
return m_idling;
}
void WorkerThread::blockUntilDone()
{
if (m_idling)
  return;
// the m_done condition variable is notified when the thread enters idle,
// which only happens when it is out of tasks and can't find any to steal
boost::unique_lock<boost::mutex> lock(m_workerMutex);
while(!m_idling)
  m_done.wait(lock);
}
void WorkerThread::thread_proc()
{
// always idle when thread first starts because
// not all other worker threads are gauranteed to
// be initialized yet, and steal() relies on that.
// Also, there shouldn't be any tasks yet anyway.
idle();
for(;;)
{
  if (!m_scheduler->m_running)
   break;
  // try to run a task. If there are not tasks available,
  // try to steal tasks.  If there are no tasks to steal
  // and the task queue is empty, then idle. If there are
  // dependency-blocked tasks, the thread does not idle.
  if (!run())
  {
   if (!steal() && m_taskCount <= 0)
	idle();
  }
}
}
BOOL WorkerThread::run()
{
if (m_taskCount <= 0)
  return false;

// Try to find a task to run. If all tasks in the queue
// have been checked, then return false so we can try to steal.
// If we have tasks waiting on dependencies, set m_dependencyBlocked
// so other WorkerThreads know not to steal from this one.
m_workerMutex.lock();
m_dependencyBlocked = false;
U32 numPops = 0;
Task* t;
while (numPops < m_taskCount)
{
  t = m_tasks.front();
  m_tasks.pop();
  if (t->isReady())
  {
   m_taskCount--;
   m_workerMutex.unlock();
   t->run();
   return true;
  }
  numPops++;
  m_tasks.push(t);
}
if (numPops > 0)
  m_dependencyBlocked = true;
m_workerMutex.unlock();
return false;
}
void WorkerThread::idle()
{
m_workerMutex.lock();
m_idling = true;
m_workerMutex.unlock();
// If another thread is waiting on us to finish execution,
// notify that this thread is done now
// Used by blockUntilDone()
m_done.notify_all();
boost::unique_lock<boost::mutex> lock(m_workerMutex);
while (m_idling)
  m_wakeUp.wait(lock);
}
BOOL WorkerThread::steal()
{
// check each worker thread for extra work
U32 workerCount = m_scheduler->m_workerCount;
for (U32 i = 0; i < workerCount; i++)
{
  WorkerThread* wt = m_scheduler->m_workers[i];
  if (wt == this || wt->m_dependencyBlocked)
   continue;
  if (wt->m_taskCount > 0)
  {
   if (stealFromWorker(wt))
	return true;
  }
}
return false;
}
BOOL WorkerThread::stealFromWorker(WorkerThread* wt)
{
while (!wt->m_workerMutex.try_lock());

// steal half of the other thread's tasks,
// rounding up. If they don't have tasks
// (the check in steal() is not guaranteed because,
// it does not lock the mutex), then return false so
// we can try another worker thread.
U32 numToSteal;
U32 taskCount = wt->m_taskCount
if (wt->m_taskCount <= 0)
{
  wt->m_workerMutex.unlock();
  return false;
}
else
  numToSteal = (wt->m_taskCount + 1) / 2;
m_workerMutex.lock();
for (U32 i = 0; i < numToSteal; i++)
{
  m_tasks.push(wt->m_tasks.front());
  wt->m_tasks.pop();
  wt->m_taskCount--;
  m_taskCount++;
}
wt->m_workerMutex.unlock();
m_workerMutex.unlock();
		return true;
}
void WorkerThread::stop()
{
m_workerMutex.lock();
m_idling = false;
m_workerMutex.unlock();
m_wakeUp.notify_all();
m_internalThread->join();
}
/// WORKER THREAD ///
//// IMPLEMENTATIONS ////


Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 16396

Like
1Likes
Like

Posted 07 May 2012 - 12:26 AM

There are several race conditions surrounding your use of state variables (e.g. m_idle). Also, spinning on try_lock() seems a bit pointless; you should instead use a blocking lock() call so that your thread can be turned off by the OS scheduler.

#3 Craig_jb   Members   -  Reputation: 181

Like
0Likes
Like

Posted 07 May 2012 - 02:10 AM

I've changed the WorkerThread implementation to avoid the race conditions. It passes testing through Helgrind at least.

https://gist.github.com/2625036

[source lang="cpp"][color=#999988][i]/// This is not written to compile. I just copied everything into one file to make viewing easy[/i][/color][color=#999988][i]/// Here is a sample usage (task definitions and implementations omitted)[/i][/color][color=#445588][b]int[/b][/color] main(){ TaskScheduler scheduler; MyTaskA taskA; MyTaskB taskB; BOOL running [b]=[/b] [b]true[/b] [b]while[/b] (running) { scheduler.pushTask([b]&[/b]taskA); scheduler.pushTask([b]&[/b]taskB); scheduler.runUntilDone(); }}[color=#999999][b]#include "boost/thread.hpp"[/b][/color][b]class[/b] [color=#445588][b]Task[/b][/color];[b]class[/b] [color=#445588][b]TaskScheduler[/b][/color];[b]class[/b] [color=#445588][b]WorkerThread[/b][/color];[color=#999988][i]//// HEADERS ////[/i][/color][color=#999988][i]/// Abstract interface for all tasks run by scheduler[/i][/color][b]class[/b] [color=#445588][b]Task[/b][/color]{[b]public[/b][b]:[/b][b]virtual[/b] [b]~[/b]Task() { }[color=#999988][i]/** Checks if all dependencies are met and the task can run[/i][/color][color=#999988][i]* @returns true if scheduler can run task, false otherwise[/i][/color][color=#999988][i]*/[/i][/color][b]virtual[/b] BOOL isReady() [b]=[/b] [color=#009999]0[/color];[color=#999988][i]/// User task code goes here[/i][/color][b]virtual[/b] [color=#445588][b]void[/b][/color] run() [b]=[/b] [color=#009999]0[/color];[color=#999988][i]/// Checks whether the task is marked complete[/i][/color]BOOL complete() { [b]return[/b] m_complete; }[color=#999988][i]/** Sets the complete status of the task[/i][/color][color=#999988][i]* @param v Completetion status[/i][/color][color=#999988][i]*/[/i][/color][color=#445588][b]void[/b][/color] setComplete(BOOL v) { m_complete [b]=[/b] v; }[b]private[/b][b]:[/b][color=#999988][i]/// Flag indicating task completion[/i][/color]BOOL m_complete;};[color=#999988][i]/// Runs Tasks across multiple threads on multiple cores[/i][/color][b]class[/b] [color=#445588][b]TaskScheduler[/b][/color]{[b]public[/b][b]:[/b][color=#999988][i]/** Create scheduler with default number of worker threads.[/i][/color][color=#999988][i]* Default is 1 thread per 1 logical core (core or HT unit)[/i][/color][color=#999988][i]*/[/i][/color]TaskScheduler();[color=#999988][i]/** Create scheduler with specified number of worker threads[/i][/color][color=#999988][i]* @param n Number of worker threads (must be less than MAX_THREADS)[/i][/color][color=#999988][i]*/[/i][/color]TaskScheduler(U32 n);[color=#999988][i]/// Finishes all currently running tasks, then stops all worker threads.[/i][/color][b]~[/b]TaskScheduler();[color=#999988][i]/** Schedules a task for execection[/i][/color][color=#999988][i]* The task is assigned to the first idle work thread if there is one;[/i][/color][color=#999988][i]* otherwise, the task is put on the queue of a worker thread. Pushed tasks[/i][/color][color=#999988][i]* execute immediately.[/i][/color][color=#999988][i]*/[/i][/color][color=#445588][b]void[/b][/color] pushTask(Task[b]*[/b] t);[color=#999988][i]/// Blocks execution until all worker threads have completed there tasks[/i][/color][color=#445588][b]void[/b][/color] runUntilDone();[color=#999988][i]/** Gets number of worker threads[/i][/color][color=#999988][i]* @return Number of worker threads[/i][/color][color=#999988][i]*/[/i][/color]U32 threadCount();[b]private[/b][b]:[/b]U32 m_workerCount;WorkerThread[b]*[/b] m_workers[MAX_THREADS];BOOL m_running;U32 m_nextPushIndex;[b]friend[/b] [b]class[/b] [color=#445588][b]WorkerThread[/b][/color];};[color=#999988][i]/** Implementation of a task-stealing worker thread for the TaskScheduler[/i][/color][color=#999988][i]* WorkerThreads steal tasks from other WorkerThreads if they are out of tasks or[/i][/color][color=#999988][i]* blocked by task dependencies. If a WorkerThread is truly out of tasks, it sleeps on a[/i][/color][color=#999988][i]* condition variable until new tasks are available.[/i][/color][color=#999988][i]*/[/i][/color][b]class[/b] [color=#445588][b]WorkerThread[/b][/color]{[b]public[/b][b]:[/b][color=#999988][i]/** Creates a new worker thread--only called by a TaskScheduler[/i][/color][color=#999988][i]* The system thread is started and enters idle, waiting on a condition variable.[/i][/color][color=#999988][i]* @param scheduler Parent TaskScheduler[/i][/color][color=#999988][i]*/[/i][/color]WorkerThread(TaskScheduler[b]*[/b] scheduler);[color=#999988][i]/// Deletes underlying system thread[/i][/color][b]~[/b]WorkerThread();[color=#999988][i]/** Adds a task to the local task pool[/i][/color][color=#999988][i]* This method is called by the TaskScheduler from the main thread and uses[/i][/color][color=#999988][i]* a spinlock to access task queue. Execution of the task can begin immediately after[/i][/color][color=#999988][i]* the lock mutex is released.[/i][/color][color=#999988][i]* @param t Task to add to queue[/i][/color][color=#999988][i]*/[/i][/color][color=#445588][b]void[/b][/color] pushTask(Task[b]*[/b] t);[color=#999988][i]/** Checks whether the worker thread is currently idling[/i][/color][color=#999988][i]* @return true if idling, false otherwise[/i][/color][color=#999988][i]*/[/i][/color]BOOL idling();[color=#999988][i]/** Blocks execution until the worker thread has completed all tasks in its queue[/i][/color][color=#999988][i]* and can no longer find tasks to steal[/i][/color][color=#999988][i]*/[/i][/color][color=#445588][b]void[/b][/color] blockUntilDone();[color=#999988][i]/** Wakes the thread and joins execution[/i][/color][color=#999988][i]* TaskScheduler must have m_running = false or method will block indefinitely[/i][/color][color=#999988][i]*/[/i][/color][color=#445588][b]void[/b][/color] stop();[b]private[/b][b]:[/b][color=#445588][b]void[/b][/color] thread_proc();BOOL run();[color=#445588][b]void[/b][/color] idle();BOOL steal();BOOL stealFromWorker(WorkerThread[b]*[/b] wt);TaskScheduler[b]*[/b] m_scheduler;boost[b]::[/b][b]thread[/b][b]*[/b] m_internalThread;boost[b]::[/b]mutex m_workerMutex;boost[b]::[/b]mutex m_idleMutex;boost[b]::[/b]condition_variable m_wakeUp;boost[b]::[/b]condition_variable m_done;std[b]::[/b]queue[b]<[/b]Task[b]*>[/b] m_tasks;U32 m_taskCount;BOOL m_idling;BOOL m_dependencyBlocked;};[color=#999988][i]//// HEADERS ////[/i][/color][color=#999988][i]//// IMPLEMENTATIONS ////[/i][/color][color=#999988][i]/// TASK SCHEDULER ///[/i][/color]TaskScheduler[b]::[/b]TaskScheduler(){m_running [b]=[/b] [b]true[/b];[color=#999988][i]// use number of 'logical cores' as default number of worker threads[/i][/color][color=#999988][i]// on CPUs with Hyperthreading, each core counts as 2[/i][/color]m_workerCount [b]=[/b] boost[b]::[/b][b]thread[/b][b]::[/b]hardware_concurrency();[b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] m_workerCount; i[b]++[/b])m_workers[i] [b]=[/b] [b]new[/b] WorkerThread([b]this[/b]);m_nextPushIndex [b]=[/b] [color=#009999]0[/color];}TaskScheduler[b]::[/b]TaskScheduler(U32 n){m_workerCount [b]=[/b] n;[b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] m_workerCount; i[b]++[/b])m_workers[i] [b]=[/b] [b]new[/b] WorkerThread([b]this[/b]);m_nextPushIndex [b]=[/b] [color=#009999]0[/color];}TaskScheduler[b]::~[/b]TaskScheduler(){m_running [b]=[/b] [b]false[/b];[b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] m_workerCount; i[b]++[/b])m_workers[i][b]->[/b]stop();}[color=#445588][b]void[/b][/color] TaskScheduler[b]::[/b]pushTask(Task[b]*[/b] t){[color=#999988][i]// try to find an idling worker thread[/i][/color][b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] m_workerCount; i[b]++[/b]){[b]if[/b] (m_workers[i][b]->[/b]idling()){m_workers[i][b]->[/b]pushTask(t);[b]return[/b];}}[color=#999988][i]// push it onto the next worker thread round-robin style[/i][/color][color=#999988][i]// if there isn't an idling thread[/i][/color]m_workers[m_nextPushIndex[b]++[/b]][b]->[/b]pushTask(t);[b]if[/b] (m_nextPushIndex [b]>=[/b] m_workerCount)m_nextPushIndex [b]=[/b] [color=#009999]0[/color];}[color=#445588][b]void[/b][/color] TaskScheduler[b]::[/b]runUntilDone(){[b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] m_workerCount; i[b]++[/b])m_workers[i][b]->[/b]blockUntilDone();}U32 TaskScheduler[b]::[/b]threadCount(){[b]return[/b] m_workerCount;}[color=#999988][i]/// TASK SCHEDULER ///[/i][/color][color=#999988][i]/// WORKER THREAD ///[/i][/color]WorkerThread[b]::[/b]WorkerThread(TaskScheduler[b]*[/b] scheduler){m_scheduler [b]=[/b] scheduler;m_taskCount [b]=[/b] [color=#009999]0[/color];m_idling [b]=[/b] [b]false[/b];m_dependencyBlocked [b]=[/b] [b]false[/b];[color=#999988][i]// creates system thread[/i][/color][color=#999988][i]// thread_proc begins execution immediately[/i][/color]m_internalThread [b]=[/b] [b]new[/b] boost[b]::[/b][b]thread[/b]([b]&[/b]WorkerThread[b]::[/b]thread_proc, [b]this[/b]);}WorkerThread[b]::~[/b]WorkerThread(){[b]delete[/b] m_internalThread;}[color=#445588][b]void[/b][/color] WorkerThread[b]::[/b]pushTask(Task[b]*[/b] t){m_workerMutex.lock();m_tasks.push(t);m_taskCount[b]++[/b];m_workerMutex.unlock();m_idleMutex.lock();m_idling [b]=[/b] [b]false[/b];m_idleMutex.unlock();[color=#999988][i]// wake up the thread if idling[/i][/color]m_wakeUp.notify_all();}BOOL WorkerThread[b]::[/b]idling(){boost[b]::[/b]lock_guard[b]<[/b]boost[b]::[/b]mutex[b]>[/b] lock(m_idleMutex);[b]return[/b] m_idling;}[color=#445588][b]void[/b][/color] WorkerThread[b]::[/b]blockUntilDone(){[color=#999988][i]// the m_done condition variable is notified when the thread enters idle,[/i][/color][color=#999988][i]// which only happens when it is out of tasks and can't find any to steal[/i][/color]boost[b]::[/b]unique_lock[b]<[/b]boost[b]::[/b]mutex[b]>[/b] lock(m_idleMutex);[b]while[/b]([b]![/b]m_idling)m_done.wait(lock);}[color=#445588][b]void[/b][/color] WorkerThread[b]::[/b]thread_proc(){[color=#999988][i]// always idle when thread first starts because[/i][/color][color=#999988][i]// not all other worker threads are gauranteed to[/i][/color][color=#999988][i]// be initialized yet, and steal() relies on that.[/i][/color][color=#999988][i]// Also, there shouldn't be any tasks yet anyway.[/i][/color]idle();[b]for[/b](;;){[b]if[/b] ([b]![/b]m_scheduler[b]->[/b]m_running)[b]break[/b];[color=#999988][i]// try to run a task. If there are not tasks available,[/i][/color][color=#999988][i]// try to steal tasks. If there are no tasks to steal[/i][/color][color=#999988][i]// and the task queue is empty, then idle. If there are[/i][/color][color=#999988][i]// dependency-blocked tasks, the thread does not idle.[/i][/color][b]if[/b] ([b]![/b]run()){[b]if[/b] ([b]![/b]steal() [b]&&[/b] m_taskCount [b]<=[/b] [color=#009999]0[/color])idle();}}}BOOL WorkerThread[b]::[/b]run(){[b]if[/b] (m_taskCount [b]<=[/b] [color=#009999]0[/color])[b]return[/b] [b]false[/b];[color=#999988][i]// Try to find a task to run. If all tasks in the queue[/i][/color][color=#999988][i]// have been checked, then return false so we can try to steal.[/i][/color][color=#999988][i]// If we have tasks waiting on dependencies, set m_dependencyBlocked[/i][/color][color=#999988][i]// so other WorkerThreads know not to steal from this one.[/i][/color]m_workerMutex.lock();m_dependencyBlocked [b]=[/b] [b]false[/b];U32 numPops [b]=[/b] [color=#009999]0[/color];Task[b]*[/b] t;[b]while[/b] (numPops [b]<[/b] m_taskCount){t [b]=[/b] m_tasks.front();m_tasks.pop();[b]if[/b] (t[b]->[/b]isReady()){m_taskCount[b]--[/b];m_workerMutex.unlock();t[b]->[/b]run();[b]return[/b] [b]true[/b];}numPops[b]++[/b];m_tasks.push(t);}[b]if[/b] (numPops [b]>[/b] [color=#009999]0[/color])m_dependencyBlocked [b]=[/b] [b]true[/b];m_workerMutex.unlock();[b]return[/b] [b]false[/b];}[color=#445588][b]void[/b][/color] WorkerThread[b]::[/b]idle(){m_idleMutex.lock();[b]if[/b] (m_taskCount [b]>[/b] [color=#009999]0[/color]){m_idleMutex.unlock();[b]return[/b];}m_idling [b]=[/b] [b]true[/b];m_idleMutex.unlock();[color=#999988][i]// If another thread is waiting on us to finish execution,[/i][/color][color=#999988][i]// notify that this thread is done now[/i][/color][color=#999988][i]// Used by blockUntilDone()[/i][/color]m_done.notify_all();boost[b]::[/b]unique_lock[b]<[/b]boost[b]::[/b]mutex[b]>[/b] lock(m_idleMutex);[b]while[/b] (m_idling)m_wakeUp.wait(lock);}BOOL WorkerThread[b]::[/b]steal(){[color=#999988][i]// check each worker thread for extra work[/i][/color]U32 workerCount [b]=[/b] m_scheduler[b]->[/b]m_workerCount;[b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] workerCount; i[b]++[/b]){WorkerThread[b]*[/b] wt [b]=[/b] m_scheduler[b]->[/b]m_workers[i];[b]if[/b] (wt [b]==[/b] [b]this[/b])[b]continue[/b];[b]if[/b] (stealFromWorker(wt))[b]return[/b] [b]true[/b];}[b]return[/b] [b]false[/b];}BOOL WorkerThread[b]::[/b]stealFromWorker(WorkerThread[b]*[/b] wt){wt[b]->[/b]m_workerMutex.lock();[color=#999988][i]// steal half of the other thread's tasks,[/i][/color][color=#999988][i]// rounding up. If they don't have tasks[/i][/color][color=#999988][i]// (the check in steal() is not guaranteed because,[/i][/color][color=#999988][i]// it does not lock the mutex), then return false so[/i][/color][color=#999988][i]// we can try another worker thread.[/i][/color]U32 numToSteal;U32 taskCount [b]=[/b] wt[b]->[/b]m_taskCount;[b]if[/b] (wt[b]->[/b]m_taskCount [b]<=[/b] [color=#009999]0[/color] [b]||[/b] wt[b]->[/b]m_dependencyBlocked){wt[b]->[/b]m_workerMutex.unlock();[b]return[/b] [b]false[/b];}[b]else[/b]numToSteal [b]=[/b] (wt[b]->[/b]m_taskCount [b]+[/b] [color=#009999]1[/color]) [b]/[/b] [color=#009999]2[/color];m_workerMutex.lock();[b]for[/b] (U32 i [b]=[/b] [color=#009999]0[/color]; i [b]<[/b] numToSteal; i[b]++[/b]){m_tasks.push(wt[b]->[/b]m_tasks.front());wt[b]->[/b]m_tasks.pop();wt[b]->[/b]m_taskCount[b]--[/b];m_taskCount[b]++[/b];}wt[b]->[/b]m_workerMutex.unlock();m_workerMutex.unlock();[b]return[/b] [b]true[/b];}[color=#445588][b]void[/b][/color] WorkerThread[b]::[/b]stop(){m_idleMutex.lock();m_idling [b]=[/b] [b]false[/b];m_idleMutex.unlock();m_wakeUp.notify_all();m_internalThread[b]->[/b]join();}[color=#999988][i]/// WORKER THREAD ///[/i][/color][color=#999988][i]//// IMPLEMENTATIONS ////[/i][/color][/source]

Edited by Craig_jb, 07 May 2012 - 02:40 AM.


#4 Oolala   Members   -  Reputation: 854

Like
0Likes
Like

Posted 07 May 2012 - 05:07 AM

These sorts of things really aren't easy to get running cleanly. There are however a whole lot of existing implementations that you might want to just use, rather than deal with this whole can of worms [unless you're doing it for practice].

Lets say you have a processor with 4 threads. You push 5 tasks into your system, where each task N blocks on a task being done by task N+1, except for the last task which is free to complete unimpeded. Your system assigns the first 4 tasks, which in turn eventually block on the completion of the 5th, which never gets scheduled.

#5 Tribad   Members   -  Reputation: 887

Like
0Likes
Like

Posted 07 May 2012 - 05:40 AM

@oolala:
Deadlocks are always a problem of multithreaded applications anyway how you manage the actiivites.

@Craig_jb:
I would maintain a special running list besides the list of tasks.
You need not searching for the running tasks anymore. On state change they move into and out of the list.
I do that for a timer list, because I have to handle some thousands of timers in parallel.

#6 Oolala   Members   -  Reputation: 854

Like
0Likes
Like

Posted 07 May 2012 - 06:06 AM

@oolala:
Deadlocks are always a problem of multithreaded applications anyway how you manage the actiivites.

True, but this is an instance where the user of the library has designed parallel code that does not contain a deadlock, but the implementation of the scheduler induces deadlock. That's a big, big distinction.

#7 Antheus   Members   -  Reputation: 2397

Like
4Likes
Like

Posted 07 May 2012 - 08:13 AM

I'm not a fan of such design or current implementation thereof.

There's still race conditions. Race conditions occur when two atomic operations occur one after another, yet they should be atomic as a unit (or transaction).

This, for example:
m_workerMutex.lock();
m_tasks.push(t);
m_taskCount++;
m_workerMutex.unlock();

<-- I steal a task here

m_idleMutex.lock();
m_idling = false;
m_idleMutex.unlock();
<-- I have no tasks, but I'm not idle

There is too much interlocked or duplicated state:
m_taskCount and m_tasks. Why?

Then there are m_workerMutex, m_idleMutex, m_wakeUp, m_done, m_idling, m_dependencyBlocked.

A thread is a state machine. All of the above can be converted into a single variable or a synchronization primitive. Draw a graph on paper on how worker works, which states it can be in and under which conditions it can transition. Such formalization also allows proof of correctness.

Querying for idle() is highly undesirable. It's serial action ("if (idle()) "). Conditions and serial execution harm the throughput. Worker knows exactly when it's idle (it's either executing a task, or it's waiting on a condition variable).

ready() - a bad idea. A thread is either executing a task or it's waiting on condition variable.

To manage dependencies, look into topological sort. Single responsibility principle and all that - workers work and no more. Deciding what and how to run is the job of scheduler. They only submit tasks once they know they can run.

Reason:
Tasks a, b;

a::ready() {
  return b->ready();
}
b::ready() {
  return a->ready();
}

As far as concurrency goes, here's a hard rule: Always acquire shared resources in same order.

If scheduler is supposed to resolve dependencies, it should do so at task level. Or, instead of opaque ready(), do something like this:
struct Task {
  vector<Task *> depends_on();
}
Using topological sort, scheduler can now determine the order in which to execute, or abort if a cycle is detected.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS