boost::thread sample code

Boost 2011. 3. 15. 17:55 Posted by zetz
게임 루프 안에서 클래스의 특정 멤버함수(오래걸리는)를 쓰레드로 빼서 처리하려고 시도 했던 테스트 코드 결론 : 생각만큼 결과가 좋진 않다. 성능상의 문제나 동기화 처리시 문제점이나..... 아직 좀더 생각해 봐야 할것 같다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/thread/xtime.hpp>
 
#include <algorithm>
#include <functional>
#include <Windows.h>
#include <vector>
 
using namespace std;
 
 
 
bool is_key_down(int v_key)
{
    return static_cast<bool>(::GetKeyState(v_key) & 0x8000);
}
 
template<typename T>
struct ThreadWorker
{
    typedef void (T::*mfptr)();
    ThreadWorker(T* pInst, mfptr job)
        : m_pInst(pInst), m_fpJob(job)
    { }
    void operator() ()
    { (m_pInst->*m_fpJob)(); }
 
    T*      m_pInst;
    mfptr   m_fpJob;
};
 
template <typename T>
class calc_square {
    T i;
public:
    calc_square() : i(0) {}
    T operator() () { ++i; return i*i; }
};
 
class CSomeClass
{
public:
    CSomeClass()
        : is_created(false), is_complate(false)
    {
        mData.resize(24, 0);
        mPivot = 0;
    };
    ~CSomeClass(){};
 
    inline void tick()
    {
        cout<< "some class in loop "<< mData[mPivot++]<< "\n";
        if (mPivot >= 24)
            mPivot = 0;
        take_sleep(1);
    }
 
 
    inline void long_time_func()
    {
        if (is_created || is_complate)  return;
 
        is_created = true;
        ThreadWorker<CSomeClass> func(this, &CSomeClass::long_time_inner);
        boost::thread work(func);
    }
 
private:
    inline void long_time_inner()
    {
        cout<< "long_time_start\n";
 
        generate(mData.begin(), mData.end(), calc_square<int>());
 
        cout<< "long_time_end\n";
        is_complate = true;
    }
 
    void    take_sleep(unsigned int sec)
    {
        boost::xtime xt;
        boost::xtime_get(&xt, boost::TIME_UTC);
        xt.sec += sec;
        boost::thread::sleep(xt);
    }
 
    bool is_created;
    bool is_complate;
 
    vector<int> mData;
    size_t      mPivot;
};
 
 
int _tmain(int argc, _TCHAR* argv[])
{
    CSomeClass cls;
 
    while (1)
    {
        if (is_key_down(27))
        {
            break;
        }
        if (is_key_down(VK_SPACE))      // load
        {
            cls.long_time_func();
        }
 
        cls.tick();
    }
 
    return 0;
}

'Boost' 카테고리의 다른 글

boost::noncopyable - 객체의 복사를 허용하지 않는 정책  (0) 2011.04.03
boost::tokenizer  (0) 2011.03.24
boost::function  (0) 2011.03.24