blob: c4ae671c9cf2d0404f1d7dd3cc548c2b769a64e2 [file] [log] [blame]
// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Abstract interfaces for threading classes that need to be implemented
// for each platform.
#ifndef SPEECH_CLIENT_SYNTHESIS_SERVICE_THREADING_H_
#define SPEECH_CLIENT_SYNTHESIS_SERVICE_THREADING_H_
namespace speech_synthesis {
// An interface for a runnable class.
// TODO(chaitanyag): Implement this using chromeos's threading library from
// third_party/chrome/base
class Runnable {
public:
virtual ~Runnable() { }
virtual void Run() = 0;
};
// A simple mutex. Only one thread can hold the lock at a time.
class Mutex {
public:
virtual ~Mutex() { }
virtual void Lock() = 0;
virtual void Unlock() = 0;
};
// A condition variable, used so that Thread B can wait until Thread A has
// signalled it to continue. Thread B locks a mutex and then checks to see
// if the variable it's looking for is ready. If not, it calls Wait,
// passing it the mutex. Meanwhile, when Thread A finishes the work it's
// doing, it locks the mutex, updates the variable, and then calls
// Signal, which instantly wakes up Thread B as soon as Thread A has
// released its lock.
class CondVar {
public:
virtual ~CondVar() { }
// The mutex MUST be locked before calling this method, and unlocked after.
virtual void Wait(Mutex* mutex) = 0;
// The mutex MUST be locked before calling this method, and unlocked after.
// Will exit after the specified number of milliseconds have passed,
// regardless of the status of the condition variable.
virtual void WaitWithTimeout(Mutex* mutex, int timeout_ms) = 0;
// The mutex MUST be locked before calling this method, and unlocked after.
virtual void Signal() = 0;
};
// A joinable thread.
class Thread {
public:
virtual ~Thread() { }
// Block until this thread has finished. Deletes this object upon return.
virtual void Join() = 0;
};
// Abstracts common functions needed for writing multithreaded programs.
class Threading {
public:
Threading()
: sleep_mutex_(NULL),
sleep_condvar_(NULL) { }
virtual ~Threading() {
delete sleep_mutex_;
delete sleep_condvar_;
}
virtual Mutex* CreateMutex();
virtual CondVar* CreateCondVar();
virtual Thread* StartJoinableThread(Runnable *action);
virtual void ThreadSleepMilliseconds(int milliseconds) {
if (!sleep_mutex_) {
sleep_mutex_ = CreateMutex();
}
if (!sleep_condvar_) {
sleep_condvar_ = CreateCondVar();
}
sleep_mutex_->Lock();
sleep_condvar_->WaitWithTimeout(sleep_mutex_, milliseconds);
sleep_mutex_->Unlock();
}
private:
Mutex* sleep_mutex_;
CondVar* sleep_condvar_;
};
} // namespace speech_synthesis
#endif // SPEECH_CLIENT_SYNTHESIS_SERVICE_THREADING_H_