Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathThread.cpp
More file actions
739 lines (629 loc) · 13.6 KB
/
Copy pathThread.cpp
File metadata and controls
739 lines (629 loc) · 13.6 KB
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//
// Thread.cpp: implementation file
//
// Copyright (C) Walter E. Capers. All rights reserved
//
// This source is free to use as you like. If you make
// any changes please keep me in the loop. Email your changes
// to walt.capers@comcast.net.
//
// PURPOSE:
//
// To implement threading as a C++ object
//
// NOTES:
// This object supports two types of thread models, event driven and
// interval driven. Under the event driven model, a thread waits
// in a paused state until the member function Event is called. When
// the Event function is called the thread wakes up and calls OnTask.
// Under the interval driven model, the thread wakes up every
// m_dwIdle milli-seconds and calls OnTask.
//
// You can switch between the two models from within the same object.
//
// COMPILER NOTES:
// On Unix you must use -lpthread a -lrt
// On Windows you must specify threaded under C++ code generation
//
// REVISIONS
// =======================================================
// Date: 10.24.07
// Name: Walter E. Capers
// Description: File creation
//
// Date: 10.24.07 11:49 am
// Name: Walter E. Capers
// Description: Added SetIdle function to allow the idle time to be altered
// independent of the SetThreadType member function.
// Added sleep interval to Stop function.
//
// Date: 10.25.07
// Name: Walter E. Capers
// Description: Added support for other non-windows platforms.
//
// Added static functions: ThreadIdsEqual and ThreadId.
//
// Added que for handling multiple events.
//
// Created the CEventClass and CMutexClass classes to facilitate
// platform independence.
//
// Date: 10.26.07
// Name: Walter E. Capers
// Description: Made object production ready...
// Added more comments
//
// Addressed various issues with threads on UNIX systems.
// -- there was a defect in the Sleep function
// -- there was a defect in the main thread function THKERNEL
// , when transitioning between thread models the CEvent::Reset
// function was not being called when it was necessary resulting
// in a lock up.
//
// Transition between thread types also failed on WINDOWS since the Event
// member function was being called from within SetThreadType. This
// resulted in an Event usage error. To correct the problem m_event.Set
// is called instead. Also, eliminated unecessary logic.
//
// Got rid of OnStart, OnStop, OnDestroy... Could not override with a derived
// class, not sure why I will come back to in a later release.
//
// Changed default behavior of thread. If OnTask is not redefined in the derived
// class the default version now expects a CTask object. The Class for CTask
// is defined in thread.h. A class must be derived from CTask to use it in
// the default version of OnTask(LPVOID).
//
//
#include "Thread.h"
#ifndef WINDOWS
extern "C"
{
int usleep(useconds_t useconds);
#ifdef NANO_SECOND_SLEEP
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
#endif
}
void Sleep( unsigned int milli )
{
#ifdef NANO_SECOND_SLEEP
struct timespec interval, remainder;
milli = milli * 1000000;
interval.tv_sec= 0;
interval.tv_nsec=milli;
nanosleep(&interval,&remainder);
#else
usleep(milli*1000);
#endif
}
#endif
#include <iostream>
using namespace std;
/**
*
* _THKERNEL
* thread callback function used by CreateThread
*
*
**/
#ifdef WINDOWS
DWORD WINAPI
#else
LPVOID
#endif
_THKERNEL( LPVOID lpvData /* CThread Object */
)
{
CThread *pThread = (CThread *)lpvData;
ThreadType_t lastType;
/*
*
* initialization
*
*/
pThread->m_mutex.Lock();
pThread->m_state = ThreadStateWaiting;
pThread->m_bRunning = TRUE;
#ifndef WINDOWS
pThread->m_dwId = CThread::ThreadId();
#endif
pThread->m_mutex.Unlock();
while( TRUE )
{
lastType = pThread->m_type;
if( lastType == ThreadTypeEventDriven )
{
if( ! pThread->m_event.Wait() )
break;
}
if( ! pThread->KernelProcess() )
break;
if( lastType == ThreadTypeEventDriven )
pThread->m_event.Reset();
if( pThread->m_type == ThreadTypeIntervalDriven )
Sleep(pThread->m_dwIdle);
}
pThread->m_mutex.Lock();
pThread->m_state = ThreadStateDown;
pThread->m_bRunning = FALSE;
pThread->m_mutex.Unlock();
#ifdef WINDOWS
return 0;
#else
return (LPVOID)0;
#endif
}
/**
*
* OnTask
* called when a thread is tasked using the Event
* member function
*
**/
BOOL
CThread::OnTask( LPVOID lpvData /*data passed from thread*/
)
{
CTask *pTask = (CTask *)lpvData;
pTask->SetTaskStatus(TaskStatusBeingProcessed);
BOOL bReturn = pTask->Task();
pTask->SetTaskStatus(TaskStatusCompleted);
return bReturn;
}
/**
*
* OnTask
* overloaded implementation of OnTask that
* takes no arguments
*
**/
BOOL
CThread::OnTask()
{
printf("\nthread is alive\n");
return TRUE;
}
BOOL
CThread::Event(CTask *pvTask /* data to be processed by thread */
)
{
ThreadId_t id;
m_mutex.Lock();
if( m_type != ThreadTypeEventDriven )
{
m_mutex.Unlock();
m_dwObjectCondition |= ILLEGAL_USE_OF_EVENT;
m_state = ThreadStateFault;
return FALSE;
}
m_mutex.Unlock();
GetId(&id);
pvTask->SetId(&id);
if( ! Push((LPVOID)pvTask) )
return FALSE;
pvTask->SetTaskStatus(TaskStatusWaitingOnQueue);
m_event.Set();
return TRUE;
}
/**
*
* Event
* wakes up a thread to process data
*
**/
BOOL
CThread::Event(LPVOID lpvData /* data to be processed by thread */
)
{
m_mutex.Lock();
if( m_type != ThreadTypeEventDriven )
{
m_mutex.Unlock();
m_dwObjectCondition |= ILLEGAL_USE_OF_EVENT;
m_state = ThreadStateFault;
return FALSE;
}
m_mutex.Unlock();
if( ! Push(lpvData) )
return FALSE;
m_event.Set();
return TRUE;
}
/**
*
* SetPriority
* sets a threads run priority, see SetThreadPriority
* Note: only works for Windows family of operating systems
*
*
**/
void
CThread::SetPriority(DWORD dwPriority)
{
#ifdef WINDOWS
SetThreadPriority(m_thread,dwPriority);
#endif
}
/**
*
* KernelProcess
* routes thread activity
*
**/
BOOL
CThread::KernelProcess()
{
m_mutex.Lock();
m_state = ThreadStateBusy;
if( !m_bRunning )
{
m_state = ThreadStateShuttingDown;
m_mutex.Unlock();
return FALSE;
}
m_mutex.Unlock();
if( !Empty() )
{
while( !Empty() )
{
Pop();
if( !OnTask(m_lpvProcessor) )
{
m_mutex.Lock();
m_lpvProcessor = NULL;
m_state = ThreadStateShuttingDown;
m_mutex.Unlock();
return FALSE;
}
}
m_mutex.Lock();
m_lpvProcessor = NULL;
m_state = ThreadStateWaiting;
}
else {
if( !OnTask() )
{
m_mutex.Lock();
m_state = ThreadStateShuttingDown;
m_mutex.Unlock();
return FALSE;
}
m_mutex.Lock();
m_state = ThreadStateWaiting;
}
m_mutex.Unlock();
return TRUE;
}
/**
*
* GetEventsPending
* returns the total number of vents waiting
* in the event que
*
**/
unsigned int
CThread::GetEventsPending()
{
unsigned int chEventsWaiting;
m_mutex.Lock();
chEventsWaiting = m_quePos;
m_mutex.Unlock();
return chEventsWaiting;
}
/**
*
* CThread
* instanciates thread object and
* starts thread.
*
**/
CThread::CThread(void)
:m_bRunning(FALSE)
#ifdef WINDOWS
,m_thread(NULL)
#endif
,m_dwId(0L)
,m_lppvQue(NULL)
,m_chQue(QUE_SIZE)
,m_quePos(0)
,m_lpvProcessor(NULL)
,m_state(ThreadStateDown)
,m_dwIdle(100)
,m_type(ThreadTypeEventDriven)
,m_stackSize(DEFAULT_STACK_SIZE)
{
m_dwObjectCondition = NO_ERRORS;
m_lppvQue = new LPVOID [QUE_SIZE];
if( !m_lppvQue )
{
m_dwObjectCondition |= MEMORY_FAULT;
m_state = ThreadStateFault;
return;
}
if( !m_mutex.m_bCreated )
{
perror("mutex creation failed");
m_dwObjectCondition |= MUTEX_CREATION;
m_state = ThreadStateFault;
return;
}
if( !m_event.m_bCreated )
{
perror("event creation failed");
m_dwObjectCondition |= EVENT_CREATION;
m_state = ThreadStateFault;
return;
}
Start();
}
/**
*
* Empty
* returns a value of TRUE if there are no items on the threads que
* otherwise a value of FALSE is returned.
*
**/
BOOL
CThread::Empty()
{
m_mutex.Lock();
if( m_quePos <= 0 )
{
m_mutex.Unlock();
return TRUE;
}
m_mutex.Unlock();
return FALSE;
}
/**
*
* Push
* place a data object in the threads que
*
**/
BOOL
CThread::Push( LPVOID lpv )
{
if( !lpv ) return TRUE;
m_mutex.Lock();
if( m_quePos+1 >= m_chQue ) {
m_mutex.Unlock();
return FALSE;
}
m_lppvQue[m_quePos++] = lpv;
m_mutex.Unlock();
return TRUE;
}
/**
*
* Pop
* move an object from the input que to the processor
*
**/
BOOL
CThread::Pop()
{
m_mutex.Lock();
if( m_quePos-1 < 0 )
{
m_quePos = 0;
m_mutex.Unlock();
return FALSE;
}
m_quePos--;
m_lpvProcessor = m_lppvQue[m_quePos];
m_mutex.Unlock();
return TRUE;
}
/**
*
* SetThreadType
* specifies the type of threading that is to be performed.
*
* ThreadTypeEventDriven (default): an event must be physically sent
* to the thread using the Event member
* function.
*
* ThreadTypeIntervalDriven : an event occurs automatically every
* dwIdle milli seconds.
*
**/
void
CThread::SetThreadType(ThreadType_t typ,
DWORD dwIdle)
{
m_mutex.Lock();
m_dwIdle = dwIdle;
if( m_type == typ ) {
m_mutex.Unlock();
return;
}
m_type = typ;
m_mutex.Unlock();
m_event.Set();
}
/**
*
* Stop
* stop thread
*
**/
void
CThread::Stop()
{
m_mutex.Lock();
m_bRunning = FALSE;
m_mutex.Unlock();
Event();
Sleep(m_dwIdle);
while(TRUE)
{
m_mutex.Lock();
if( m_state == ThreadStateDown )
{
m_mutex.Unlock();
return;
}
m_mutex.Unlock();
Sleep(m_dwIdle);
}
}
/**
*
* SetIdle
* changes the threads idle interval
*
**/
void
CThread::SetIdle(DWORD dwIdle)
{
m_mutex.Lock();
m_dwIdle = dwIdle;
m_mutex.Unlock();
}
/**
*
* Start
* start thread
*
**/
BOOL
CThread::Start()
{
m_mutex.Lock();
if( m_bRunning )
{
m_mutex.Unlock();
return TRUE;
}
m_mutex.Unlock();
if( m_dwObjectCondition & THREAD_CREATION )
m_dwObjectCondition = m_dwObjectCondition ^ THREAD_CREATION;
#ifdef WINDOWS
if( m_thread ) CloseHandle(m_thread);
m_thread = CreateThread(NULL,m_stackSize ,_THKERNEL,(LPVOID)this,0,&m_dwId);
if( !m_thread )
{
perror("thread creating failed");
m_dwObjectCondition |= THREAD_CREATION;
m_state = ThreadStateFault;
return FALSE;
}
#else
pthread_attr_t attr;
pthread_attr_init(&attr);
#ifdef VMS
if( m_stackSize == 0 )
pthread_attr_setstacksize(&attr,PTHREAD_STACK_MIN*10);
#endif
if( m_stackSize != 0 )
pthread_attr_setstacksize(&attr,m_stackSize);
int error = pthread_create(&m_thread,&attr,_THKERNEL,(LPVOID)this);
if( error != 0 )
{
m_dwObjectCondition |= THREAD_CREATION;
m_state = ThreadStateFault;
#if defined(HPUX) || defined(SUNOS) || defined(LINUX)
switch(error)/* show the thread error */
{
case EINVAL:
cerr << "error: attr in an invalid thread attributes object\n";
break;
case EAGAIN:
cerr << "error: the necessary resources to create a thread are not\n";
cerr << "available.\n";
break;
case EPERM:
cerr << "error: the caller does not have the privileges to create\n";
cerr << "the thread with the specified attr object.\n";
break;
#if defined(HPUX)
case ENOSYS:
cerr << "error: pthread_create not implemented!\n";
if( __is_threadlib_linked()==0 )
{
cerr << "error: threaded library not being used, improper linkage \"-lpthread -lc\"!\n";
}
break;
#endif
default:
cerr << "error: an unknown error was encountered attempting to create\n";
cerr << "the requested thread.\n";
break;
}
#else
cerr << "error: could not create thread, pthread_create failed (" << error << ")!\n";
#endif
return FALSE;
}
#endif
return TRUE;
}
/**
*
* ThreadState
* return the current state of the thread
*
**/
ThreadState_t
CThread::ThreadState()
{
ThreadState_t currentState;
m_mutex.Lock();
currentState = m_state;
m_mutex.Unlock();
return currentState;
}
/**
*
* ~CThread
* destructor. Stop should be called prior to destruction to
* allow for gracefull thread termination.
*
**/
CThread::~CThread(void)
{
#ifdef WINDOWS
if( m_bRunning )
{
// TerminateThread(m_thread,1); brutal termination
Stop(); // gracefull terminatation
WaitForSingleObject(m_thread,INFINITE);
}
CloseHandle(m_thread);
#else
LPVOID lpv;
if( m_bRunning )
{
Stop();
pthread_join(m_thread,&lpv);
}
#endif
delete [] m_lppvQue;
}
/**
*
* PingThread
* used to determine if a thread is running
*
**/
BOOL
CThread::PingThread(DWORD dwTimeout /* timeout in milli-seconds */
)
{
DWORD dwTotal = 0;
while(TRUE)
{
if( dwTotal > dwTimeout && dwTimeout > 0 )
return FALSE;
m_mutex.Lock();
if( m_bRunning )
{
m_mutex.Unlock();
return TRUE;
}
dwTotal += m_dwIdle;
m_mutex.Unlock();
Sleep(m_dwIdle);
}
return FALSE;
}
You can’t perform that action at this time.
