• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "webrtc/base/worker.h"
12 
13 #include "webrtc/base/common.h"
14 #include "webrtc/base/logging.h"
15 #include "webrtc/base/thread.h"
16 
17 namespace rtc {
18 
19 enum {
20   MSG_HAVEWORK = 0,
21 };
22 
Worker()23 Worker::Worker() : worker_thread_(NULL) {}
24 
~Worker()25 Worker::~Worker() {
26   // We need to already be stopped before being destroyed. We cannot call
27   // StopWork() from here because the subclass's data has already been
28   // destructed, so OnStop() cannot be called.
29   ASSERT(!worker_thread_);
30 }
31 
StartWork()32 bool Worker::StartWork() {
33   rtc::Thread *me = rtc::Thread::Current();
34   if (worker_thread_) {
35     if (worker_thread_ == me) {
36       // Already working on this thread, so nothing to do.
37       return true;
38     } else {
39       LOG(LS_ERROR) << "Automatically switching threads is not supported";
40       ASSERT(false);
41       return false;
42     }
43   }
44   worker_thread_ = me;
45   OnStart();
46   return true;
47 }
48 
StopWork()49 bool Worker::StopWork() {
50   if (!worker_thread_) {
51     // Already not working, so nothing to do.
52     return true;
53   } else if (worker_thread_ != rtc::Thread::Current()) {
54     LOG(LS_ERROR) << "Stopping from a different thread is not supported";
55     ASSERT(false);
56     return false;
57   }
58   OnStop();
59   worker_thread_->Clear(this, MSG_HAVEWORK);
60   worker_thread_ = NULL;
61   return true;
62 }
63 
HaveWork()64 void Worker::HaveWork() {
65   ASSERT(worker_thread_ != NULL);
66   worker_thread_->Post(this, MSG_HAVEWORK);
67 }
68 
OnMessage(rtc::Message * msg)69 void Worker::OnMessage(rtc::Message *msg) {
70   ASSERT(msg->message_id == MSG_HAVEWORK);
71   ASSERT(worker_thread_ == rtc::Thread::Current());
72   OnHaveWork();
73 }
74 
75 }  // namespace rtc
76