在创建好Thread对象后,调用Start(rtc::Runnable *runnable)接口启动时,设置runnable参数:
如果runnable = NULL,则线程使用自带的消息处理函数ProcessMessage,通过向线程Post消息来执行任务
如果runnable 不为空,则线程使用runnable的Run()函数作为其线程函数,通过实现Runnable接口的Run()函数实现
class TestRunnable : virtual public rtc::Runnable
{
public:
virtual void Run(Thread* thread)
{
while (running_)
{
rtc::Thread::SleepMs(1000);
std::cout << "This is sub thread ..." << std::endl;
}
int i = 0;
}
void StopRunning() { running_ = false; }
bool running_ = true;
}
TestRunnable *test_runnable_;
std::unique_ptr<rtc::Thread> thread_;
void main()
{
test_runnable_ = new TestRunnable();
thread_ = rtc::Thread::Create();
thread_->SetName("Test Thread", NULL);
thread_->Start(test_runnable_);
int nCount = 0;
while (true)
{
Sleep(2000);
std::cout << "This is main thread ..." << std::endl;
nCount++;
if (nCount > 2)
{
break;
}
}
test_runnable_->StopRunning();
thread_->Stop();
int a = 0;
}