如果不使用 aPoco::Thread
而是使用 a Poco::Task
,则会得到一个可以取消的线程。以下示例代码(准备好按原样运行)应该会给您一个想法:
#include <Poco/Task.h>
#include <Poco/TaskManager.h>
#include <Poco/Thread.h>
#include <string>
#include <iostream>
using namespace std;
class UdpListenerTask : public Poco::Task {
public:
UdpListenerTask(const string& name) : Task(name) { }
void runTask() {
cout << name() << ": starting" << endl;
while (! isCancelled()) {
// Do some work. Cannot block indefinitely, otherwise it
// will never test the isCancelled() condition.
doSomeWork();
}
cout << endl << name() << ": cancelled " << endl;
}
private:
int doSomeWork() {
cout << "*" << flush;
// Simulate some time spent doing work
int i;
for (i = 0; i < INT32_MAX/1000; i++) { }
return i;
}
};
void runUdpProbe() {
// Simulate some time spent running the probe.
Poco::Thread::sleep(1000);
}
int main() {
Poco::TaskManager tm;
UdpListenerTask* st = new UdpListenerTask("task1");
tm.start(st); // tm takes ownership
// Run test 1.
runUdpProbe();
// Test 1 done. Cancel the UDP listener
st->cancel();
// Run all the other tests
// cleanup
tm.joinAll();
return 0;
}
POCO 幻灯片Multithreading给出了 Poco::Thread 和 Poco::Task 的用法示例。
顺便说一句,单元测试应该通过抽象类和模拟对象绕过 UDP 通信;我认为这个测试应该被称为特性测试:-)