1 | #include <iostream>
|
---|
2 | #include <string>
|
---|
3 |
|
---|
4 | #include <boost/thread.hpp>
|
---|
5 |
|
---|
6 | using namespace std;
|
---|
7 |
|
---|
8 | class iCallable
|
---|
9 | {
|
---|
10 | public:
|
---|
11 | virtual void operator()(const string& name) = 0;
|
---|
12 | };
|
---|
13 |
|
---|
14 | typedef boost::thread cThread;
|
---|
15 |
|
---|
16 | typedef boost::mutex cMutex;
|
---|
17 |
|
---|
18 | typedef boost::lock_guard<boost::mutex> cLock;
|
---|
19 |
|
---|
20 | typedef map<string,cThread*> cThreadMap;
|
---|
21 |
|
---|
22 | cThreadMap m_threads;
|
---|
23 |
|
---|
24 | template<class T>
|
---|
25 | void startThread(const string& thread_name)
|
---|
26 | {
|
---|
27 | T obj;
|
---|
28 | m_threads[thread_name] = new cThread(obj, thread_name);
|
---|
29 | }
|
---|
30 |
|
---|
31 | bool stopThread(const string& thread_name)
|
---|
32 | {
|
---|
33 |
|
---|
34 | cThreadMap::iterator it = m_threads.find(thread_name);
|
---|
35 | if (it != m_threads.end())
|
---|
36 | {
|
---|
37 | it->second->interrupt();
|
---|
38 | it->second->join();
|
---|
39 | delete it->second;
|
---|
40 | m_threads.erase(it);
|
---|
41 | return true;
|
---|
42 | }
|
---|
43 | else
|
---|
44 | {
|
---|
45 | return false;
|
---|
46 | }
|
---|
47 | }
|
---|
48 |
|
---|
49 | class cTestRunner : public iCallable
|
---|
50 | {
|
---|
51 | public:
|
---|
52 | virtual void operator()(const string& name)
|
---|
53 | {
|
---|
54 | for (;;)
|
---|
55 | {
|
---|
56 | boost::this_thread::sleep(boost::posix_time::microseconds(500));
|
---|
57 | }
|
---|
58 | }
|
---|
59 | };
|
---|
60 |
|
---|
61 | int main()
|
---|
62 | {
|
---|
63 | startThread<cTestRunner>("a");
|
---|
64 |
|
---|
65 | boost::this_thread::sleep(boost::posix_time::milliseconds(500));
|
---|
66 |
|
---|
67 | stopThread("a");
|
---|
68 |
|
---|
69 | return 0;
|
---|
70 | }
|
---|