~smspillaz/nux/nux.fix_1036521

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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#ifndef NTHREAD_H
#define NTHREAD_H

#include "NObjectType.h"

NAMESPACE_BEGIN

class NThreadSafeCounter
{   
public:
    NThreadSafeCounter() {m_Counter = 0;}
    NThreadSafeCounter(t_integer i) {m_Counter = i;}
    t_integer Increment();
    t_integer Decrement();
    t_integer Set(t_integer i);
    t_integer GetValue() const;
    t_integer operator ++ ();
    t_integer operator -- ();
    t_bool operator == (t_integer i);
private:
    t_integer m_Counter;
};

class NCriticalSection
{
public:
    //! Initialize critical section.
    /*!
        Initialize critical section.
    */
    NCriticalSection() { InitializeCriticalSection(&m_lock); }

    //! Destroy critical section.
    /*!
        Destroy critical section.
    */
    ~NCriticalSection() { DeleteCriticalSection(&m_lock); }

    //! Enter critical section.
    /*!
        Enter critical section. This function is made const so it can be used without restriction.
        For that matter, m_lock is made mutable.
    */
    void Lock() const
    {
        EnterCriticalSection(&m_lock);
    }

    //! Leave critical section.
    /*!
        Leave critical section. This function is made const so it can be used without restriction.
        For that matter, m_lock is made mutable.
    */
    void Unlock() const
    {
        LeaveCriticalSection(&m_lock);
    }

private:
    //! Prohibit copy constructor.
    /*!
        Prohibit copy constructor.
    */
    NCriticalSection(const NCriticalSection&);
    //! Prohibit assignment operator.
    /*!
        Prohibit assignment operator.
    */
    NCriticalSection& operator=(const NCriticalSection&);

    mutable CRITICAL_SECTION m_lock;
};

//! Scope Lock class
/*!
    Takes a critical section object as parameter of the constructor.
    The constructor locks the critical section.
    The destructor unlocks the critical section.
*/
class NScopeLock
{
public:
    //! The constructor locks the critical section object.
    /*!
        The constructor locks the critical section object.
        @param  LockObject      Critical section object.
    */
    NScopeLock(NCriticalSection* CriticalSectionObject)
        : m_CriticalSectionObject(CriticalSectionObject)
    {
        nuxAssert(m_CriticalSectionObject);
        m_CriticalSectionObject->Lock();
    }

    //! The destructor unlocks the critical section object.
    /*!
        The destructor unlocks the critical section object.
    */
    ~NScopeLock(void)
    {
        nuxAssert(m_CriticalSectionObject);
        m_CriticalSectionObject->Unlock();
    }

private:
    //! Prohibit default constructor.
    /*!
        Prohibit default constructor.
    */
    NScopeLock(void);

    //! Prohibit copy constructor.
    /*!
        Prohibit copy constructor.
    */
    NScopeLock(const NScopeLock& ScopeLockObject);

    //! Prohibit assignment operator.
    /*!
        Prohibit assignment operator.
    */
    NScopeLock& operator=(const NScopeLock& ScopeLockObject) { return *this; }

    //! Critical section Object.
    /*!
        Critical section Object.
    */
    NCriticalSection* m_CriticalSectionObject;
};

class NThreadLocalStorage
{
public:
    enum
    {
        NbTLS = 128,
        InvalidTLS = 0xFFFFFFFF
    };

    typedef void (*TLS_ShutdownCallback)();
    
    static BOOL                     m_TLSUsed[NbTLS];
    static t_u32                     m_TLSIndex[NbTLS];
    static TLS_ShutdownCallback     m_TLSCallbacks[NbTLS];
    
    static void Initialize();
    static void Shutdown();
    static BOOL RegisterTLS(t_u32 index, TLS_ShutdownCallback shutdownCallback);
    static void ThreadInit();
    static void ThreadShutdown();

public:

    template<class T> static inline T GetData(t_u32 index)
    {
        nuxAssert(sizeof(T) <= sizeof(size_t));				
        nuxAssert(index < NbTLS);
        nuxAssert(m_TLSUsed[index]);

        // T and (unsigned long) can be of different sizes
        // but this limits the use of GetData to classes without copy constructors
        union
        {
            T               t;
            void*           v;
        } temp;
        temp.v = TlsGetValue(m_TLSIndex[index]);
        return temp.t;
    }

    template<class T> static inline void SetData(t_u32 index, T value)
    {
        nuxAssert(sizeof(T) <= sizeof(size_t));				
        nuxAssert(index < NbTLS);
        nuxAssert(m_TLSUsed[index]);

        // T and (unsigned long) can be of different sizes
        // but this limits the use of GetData to classes without copy constructors
        union{
            T               t;
            void*           v;
        } temp;
        temp.t = value;
        BOOL b = TlsSetValue(m_TLSIndex[index], temp.v);
        nuxAssertMsg(b, TEXT("[NThreadLocalStorage::SetData] TlsSetValue returned FALSE."));
    }
};

#define inlDeclareThreadLocalStorage(type, index, name)	\
struct		ThreadLocalStorageDef##name { enum Const { Index = index}; };\
inline		type GetTLS_##name() { return nux::NThreadLocalStorage::GetData<type>(ThreadLocalStorageDef##name::Index); }\
inline		void SetTLS_##name(type value) { nux::NThreadLocalStorage::SetData<type>(ThreadLocalStorageDef##name::Index, value); }

#define inlRegisterThreadLocalIndex(index, name, shutdownCallback) \
    nuxVerifyExpr(index == ThreadLocalStorageDef##name::Index); \
    nuxVerifyExpr(nux::NThreadLocalStorage::RegisterTLS(index, shutdownCallback)) 

#define inlGetThreadLocalStorage(name)			GetTLS_##name()
#define inlSetThreadLocalStorage(name, value)  SetTLS_##name(value)

#ifdef POP_CHECK_THREADS
#define	nuxAssertInsideThread(threadtype)	             nuxAssert( inlGetThreadLocalStorage(ThreadType) == threadtype)
#define	nuxAssertInsideThread2(threadtype1, threadtype2) nuxAssert( inlGetThreadLocalStorage(ThreadType) == threadtype1 || popGetThreadLocalData(ThreadType) == threadtype2)
#define nuxAssertNotInsideThread(threadtype)             nuxAssert( inlGetThreadLocalStorage(ThreadType) != threadtype)
#else
#define	nuxAssertInsideThread(threadtype)	((void) 0)
#define	nuxAssertInsideThread2(threadtype1, threadtype2)	((void) 0)
#define nuxAssertNotInsideThread(threadtype) ((void) 0)
#endif

void SetWin32ThreadName(DWORD dwThreadID, LPCSTR szThreadName);


typedef enum
{
    THREADINIT,
    THREADRUNNING,
    THREADSUSPENDED,
    THREADSTOP,
    THREAD_START_ERROR,
    THREAD_STOP_ERROR,
    THREAD_SUSPEND_ERROR,
    THREAD_RESUME_ERROR,
} ThreadState;

// http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c3793/
class NThread
{
    DECLARE_ROOT_OBJECT_TYPE(NThread);
public:
    /*!
    	Info: Default Constructor
    */
    NThread();

    /*!
        Info: Plug Constructor

        Use this to migrate/port existing worker threads to objects immediately
        Although you lose the benefits of ThreadCTOR and ThreadDTOR.
    */
    NThread(LPTHREAD_START_ROUTINE lpExternalRoutine);

    /*!
        Info: Default Destructor

        I think it is wise to destroy the thread even if it is running,
        when the main thread reaches here.
    */
    virtual ~NThread();

    /*!
        Info: Starts the thread.

        This function starts the thread pointed by m_pThreadFunc with default attributes
    */
    virtual ThreadState Start( void* arg = NULL );

    /*!
        Info: Stops the thread.

        This function stops the current thread. 
        We can force kill a thread which results in a TerminateThread.
    */
    virtual ThreadState Stop ( bool bForceKill = false );

    ThreadState Suspend();
    ThreadState Resume();
    ThreadState ResumeStart();
    ThreadState ResumeExit();

    /*!
        Info: Starts the thread.

        This function starts the thread pointed by m_pThreadFunc with default attributes
    */
    t_u32 GetExitCode() const;

    /*!
        Info: Attaches a Thread Function

        Used primarily for porting but can serve in developing generic thread objects
    */
    void Attach( LPTHREAD_START_ROUTINE lpThreadFunc ){
        m_pThreadFunc = lpThreadFunc;
    }

    /*!
        Info: Detaches the Attached Thread Function

        Detaches the Attached Thread Function, If any.
        by resetting the thread function pointer to EntryPoint1
    */
    void  Detach( void )
    {
        m_pThreadFunc = NThread::EntryPoint; 
    }

    HANDLE GetThreadHandle();
    t_u32 GetThreadId();


    ThreadState GetThreadState() const;
    void SetThreadState(ThreadState state);

    void SetThreadName(const TCHAR* ThreadName);
    const NString& GetThreadName() const;

protected:
    NString m_ThreadName;

    volatile ThreadState m_ThreadState;

    /*!
        Info: DONT override this method.
        
        This function is like a standard template. 
        Override if you are sure of what you are doing.
        
        In C++ the entry function of a thread cannot be a normal member function of a class. 
        However, it can be a static member function of a class. This is what we will use as the entry point.
        There is a gotcha here though. Static member functions do not have access to the this pointer of a C++ object.
        They can only access static data. Fortunately, there is way to do it. Thread entry point functions take a void * as
        a parameter so that the caller can typecast any data and pass in to the thread. We will use this to pass this to
        the static function. The static function will then typecast the void * and use it to call a non static member function
    */
    static DWORD WINAPI EntryPoint(void* pArg);

    /*!
        Info: Override this method.

        This function should contain the body/code of your thread.
        Notice the signature is similar to that of any worker thread function
        except for the calling convention.
    */
    virtual t_u32 Run(void* /* arg */ )
    { return m_ThreadCtx.m_dwExitCode; }

    /*!
        Info: Constructor-like function. 

        Will be called by EntryPoint before executing the thread body.
        Override this function to provide your extra initialization.

        NOTE: do not confuse it with the classes constructor
        @return TRUE if the thread can continue running the program. If FALSE is returned, the thread won't execute the main body Run() and will exit without calling ThreadDtor.
    */
    virtual bool ThreadCtor(){return true;}

    /*!
        Info: Destructor-like function. 

        Will be called by EntryPoint after executing the thread body.
        Override this function to provide your extra destruction.

        NOTE: do not confuse it with the classes constructor
        @return TRUE if this function executed without problems.
    */
    virtual bool ThreadDtor(){return true;}

private:
    /*!
        Info: Thread Context Inner Class

        Every thread object needs to be associated with a set of values.
        like UserData Pointer, Handle, Thread ID etc.

        NOTE: This class can be enhanced to varying functionalities
        eg.,
            * Members to hold StackSize
            * SECURITY_ATTRIBUTES member.
    */
    class NThreadContext
    {
    public:
        NThreadContext(){
            memset(this, 0, sizeof(this));
        }

        /*
        *	Attributes Section
        */
    public:
        HANDLE m_hThread;					//	The Thread Handle
        volatile t_u32  m_dwTID;						//	The Thread ID
        void* m_pUserData;						//	The user data pointer
        void* m_pParent;					//	The this pointer of the parent NThread object
        t_u32  m_dwExitCode;				//	The Exit Code of the thread
    };

    /*!
        Attributes Section
    */
protected:
    /*!
        Info: Members of NThread
    */
    NThreadContext			m_ThreadCtx;	//	The Thread Context member
    LPTHREAD_START_ROUTINE	m_pThreadFunc;	//	The Worker Thread Function Pointer
};

//  USAGE:
//    DWORD WINAPI Threaded(void* lpData);
//
//    class CDemoThread : public CThread
//    {
//        virtual t_u32 Run( void* /* arg */ )
//        { 
//            for(;;)
//            {
//                printf("Threaded Object Code \n");
//                Sleep(1000);
//            }
//        }
//    };
//
//    void main( void )
//    {
//        CDemoThread dmt;
//        dmt.Start(NULL);
//        SleepEx(15 * 1000, FALSE);
//        dmt.Stop(true);
//
//        //	A Sample Code for porting existent code of Threaded function
//        CThread t1(Threaded), t2;
//        t2.Attach(Threaded);
//        t1.Start();
//        t2.Start();
//        SleepEx(15 * 1000, FALSE);
//        t2.Stop();
//        t1.Stop();
//    }
//
//    DWORD WINAPI Threaded( void* /* lpData */ )
//    {
//        for(;;)
//        {
//            printf("worker threaded code");
//            Sleep(1000);
//        }
//    }

NAMESPACE_END

#endif // NTHREAD_H