File: tjthread.cpp

package info (click to toggle)
odin 2.0.5-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,196 kB
  • sloc: cpp: 62,638; sh: 4,541; makefile: 779
file content (612 lines) | stat: -rw-r--r-- 14,511 bytes parent folder | download | duplicates (4)
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
#include "tjthread.h"
#include "tjtools.h"
#include "tjtest.h"
#include "tjindex.h"
#include "tjthread_code.h"
#include "tjlog_code.h"

#ifndef NO_THREADS


#ifdef USING_WIN32
#include <windows.h>
#define USE_WINTHREADS
#else
#ifdef HAVE_PTHREAD
#include <pthread.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h> // for sysconf
#endif
#define USE_PTHREADS
#endif
#endif


#endif



const char* ThreadComponent::get_compName() {return "Thread";}
LOGGROUNDWORK(ThreadComponent)

////////////////////////////////////////////////////////////////////

#ifdef USE_PTHREADS
const char* pthread_err(int code) {
  if(code==EAGAIN) return "not enough system resources to create a process for the new thread.";
  if(code==ESRCH) return "No thread could be found corresponding to that specified by |th|.";
  if(code==EINVAL) return "The |th| thread has been detached./the mutex has not been properly initialized.";
  if(code==EINVAL) return "Another thread is already waiting on termination of |th|.";
  if(code==EDEADLK) return "The |th| argument refers to the calling thread./the mutex is already locked by the calling thread.";
  if(code==EBUSY) return "the mutex could not be acquired because it was currently locked./some threads are currently waiting on |cond|";
  if(code==EPERM) return "the calling thread does not own the mutex.";
  if(code==ETIMEDOUT) return "the condition variable was not signaled until the timeout specified by |abstime|";
  if(code==EINTR) return "!pthread_cond_timedwait! was interrupted by a signal";
  if(code==ENOMEM) return "Out of memory";
  return "Unknown error";
}
#endif

////////////////////////////////////////////////////////////////////

Mutex::Mutex() : id(0) {
  // Do not use Log in here since SingletonHandler uses Mutex
#ifdef USE_PTHREADS
#ifdef MACOS // the Mac OS way of creating recursive threads
  pthread_mutexattr_t pma_recursive;
  int errcode=pthread_mutexattr_init(&pma_recursive);
  if(errcode) {
    STD_cerr << "ERROR: Mutex: " << pthread_err(errcode) << STD_endl;
    return;
  }
  errcode=pthread_mutexattr_settype(&pma_recursive, PTHREAD_MUTEX_RECURSIVE);
  if(errcode) {
    STD_cerr << "ERROR: Mutex: " << pthread_err(errcode) << STD_endl;
    return;
  }
  id=(void*)new pthread_mutex_t;
  errcode=pthread_mutex_init((pthread_mutex_t*)id, &pma_recursive);
  if(errcode) {
    STD_cerr << "ERROR: Mutex: " << pthread_err(errcode) << STD_endl;
    return;
  }
#else  // the Linux way of creating recursive threads
  pthread_mutex_t pm_recursive=PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
  id=(void*)new pthread_mutex_t(pm_recursive);
#endif
#endif
#ifdef USE_WINTHREADS
  CRITICAL_SECTION* cs=new CRITICAL_SECTION;
  InitializeCriticalSection(cs);
  id=(void*)cs;
#endif
}


Mutex::~Mutex() {
  // Do not use Log in here since SingletonHandler uses Mutex
  if(id) {
#ifdef USE_PTHREADS
    int errcode=pthread_mutex_destroy((pthread_mutex_t*)id);
    if(errcode) STD_cerr << "ERROR: ~Mutex: " << pthread_err(errcode) << STD_endl;
    delete (pthread_mutex_t*)id;
#endif
#ifdef USE_WINTHREADS
    DeleteCriticalSection((CRITICAL_SECTION*)id);
    delete (CRITICAL_SECTION*)id;
#endif
  }
}


void Mutex::lock() {
  // Do not use Log in here since SingletonHandler uses Mutex
  if(id) {
#ifdef USE_PTHREADS
    int errcode=pthread_mutex_lock((pthread_mutex_t*)id);
    if(errcode) STD_cerr << "ERROR: Mutex::lock: " << pthread_err(errcode) << STD_endl;
#endif
#ifdef USE_WINTHREADS
    EnterCriticalSection((CRITICAL_SECTION*)id);
#endif
  }
}

void Mutex::unlock() {
  // Do not use Log in here since SingletonHandler uses Mutex
  if(id) {
#ifdef USE_PTHREADS
    int errcode=pthread_mutex_unlock((pthread_mutex_t*)id);
    if(errcode) STD_cerr << "ERROR: Mutex::unlock: " << pthread_err(errcode) << STD_endl;
#endif
#ifdef USE_WINTHREADS
    LeaveCriticalSection((CRITICAL_SECTION*)id);
#endif
  }
}

////////////////////////////////////////////////////////////////////


Event::Event() : id(0), active(false) {
  Log<ThreadComponent> odinlog("Event","Event");
#ifdef USE_PTHREADS
  id=(void*)new pthread_cond_t;
  int errcode=pthread_cond_init((pthread_cond_t*)id, NULL);
  if(errcode) {
    ODINLOG(odinlog,errorLog) << pthread_err(errcode) << STD_endl;
  }
#endif
#ifdef USE_WINTHREADS
  id=(void*)new HANDLE;
  *((HANDLE*)id)=CreateEvent(NULL,TRUE,FALSE,NULL);
#endif
}

Event::~Event() {
  Log<ThreadComponent> odinlog("Event","~Event");
  if(id) {
#ifdef USE_PTHREADS
    int errcode=pthread_cond_destroy((pthread_cond_t*)id);
    if(errcode) {
      ODINLOG(odinlog,errorLog) << pthread_err(errcode) << STD_endl;
    }
    delete (pthread_cond_t*)id;
#endif
#ifdef USE_WINTHREADS
    CloseHandle(*((HANDLE*)id));
    delete (HANDLE*)id;
#endif
  }
}


void Event::wait() {
  Log<ThreadComponent> odinlog("Event","wait");
#ifdef USE_PTHREADS
  MutexLock lock(mutex);
  while(!active) {
    int errcode=pthread_cond_wait((pthread_cond_t*)id, (pthread_mutex_t*)(mutex.id));
    if(errcode) {
      ODINLOG(odinlog,errorLog) << pthread_err(errcode) << STD_endl;
      break;
    }
  }
#endif
#ifdef USE_WINTHREADS
  WaitForSingleObject(*((HANDLE*)id), INFINITE);
#endif
}


void Event::signal() {
  Log<ThreadComponent> odinlog("Event","signal");
#ifdef USE_PTHREADS
  MutexLock lock(mutex);
  active=true;
  int errcode=pthread_cond_broadcast((pthread_cond_t*)id);
  if(errcode) {
    ODINLOG(odinlog,errorLog) << pthread_err(errcode) << STD_endl;
  }
#endif
#ifdef USE_WINTHREADS
  SetEvent(*((HANDLE*)id));
#endif
}

void Event::reset() {
  Log<ThreadComponent> odinlog("Event","reset");
#ifdef USE_PTHREADS
  MutexLock lock(mutex);
  active=false;
#endif
#ifdef USE_WINTHREADS
  ResetEvent(*((HANDLE*)id));
#endif
}



////////////////////////////////////////////////////////////////////



// pthread_t cannot be converted to an integer on all platforms (e.g. Darwin) so we need a separate map
#ifdef USE_PTHREADS
static STD_map<int,pthread_t> pthreadindexmap;
static Mutex pthreadindexmutex;

struct ThreadIndex  : public UniqueIndex<ThreadIndex> {

  // functions for UniqueIndex
  static const char* get_typename() {return "ThreadIndex";}
  static unsigned int get_max_instances() {return 0;}
};
#endif

//////////////////////////


#ifdef USE_WINTHREADS
DWORD WINAPI start_thread(LPVOID t) {
#else
void* start_thread(void* t) {
#endif
  ((Thread*)t)->run();
  return 0;
}

//////////////////////////


Thread::Thread() : id(0) {
#ifdef USE_PTHREADS
  index=new ThreadIndex;
#endif
}

Thread::~Thread() {
  clear_id();
#ifdef USE_PTHREADS
  delete index;
#endif
}


void Thread::clear_id() {
  if(id) {
#ifdef USE_PTHREADS
    delete ((pthread_t*)id);
#endif
#ifdef USE_WINTHREADS
    delete ((HANDLE*)id);
#endif
  }
  id=0;
}

bool Thread::start(unsigned int stack_size) {
  Log<ThreadComponent> odinlog("Thread","start");
  wait(); // will clear id

#ifdef USE_PTHREADS
  id=(void*)new pthread_t;
  pthread_attr_t pt_attr;
  int errcode=pthread_attr_init (&pt_attr);
  if(errcode) {
    ODINLOG(odinlog,errorLog) << "pthread_attr_init: " << pthread_err(errcode) << STD_endl;
    return false;
  }
  if(stack_size)  {
    errcode=pthread_attr_setstacksize (&pt_attr, stack_size);
    if(errcode) {
      ODINLOG(odinlog,errorLog) << "pthread_attr_setstacksize: " << pthread_err(errcode) << STD_endl;
      return false;
    }
  }
  errcode=pthread_create((pthread_t*)id, &pt_attr, &start_thread, this);
  if(errcode) {
    ODINLOG(odinlog,errorLog) << "pthread_create: " << pthread_err(errcode) << STD_endl;
#ifdef HAVE_SYSCONF
    ODINLOG(odinlog,errorLog) << "PTHREAD_THREADS_MAX=" << sysconf(_SC_THREAD_THREADS_MAX) << STD_endl;
#endif
    return false;
  }
  pthreadindexmutex.lock(); // lock because other threads might already be running
  pthreadindexmap[index->get_index()]=*((pthread_t*)id);
  pthreadindexmutex.unlock();
#else
#ifdef USE_WINTHREADS
  HANDLE* handle=new HANDLE;
  (*handle)=CreateThread(NULL,stack_size,&start_thread,this,0,NULL);
  id=(void*)handle;
  if(*handle==NULL) {
    ODINLOG(odinlog,errorLog) << "CreateThread: " << lasterr() << STD_endl;
    return false;
  }
#else
  this->run(); // no threads
#endif
#endif
  return true;
}


bool Thread::wait() {
  Log<ThreadComponent> odinlog("Thread","wait");
#ifdef USE_PTHREADS
  int errcode=0;
  if(id) {
    void* returnval;
    errcode=pthread_join(*((pthread_t*)id), &returnval);
    ODINLOG(odinlog,normalDebug) << "errcode=" << errcode << STD_endl;
  }
  clear_id();
  if(errcode) {
    ODINLOG(odinlog,errorLog) << pthread_err(errcode) << STD_endl;
    return false;
  }
#endif
#ifdef USE_WINTHREADS
  if(id) {
    DWORD errcode=WaitForSingleObject(*((HANDLE*)id),INFINITE);
    clear_id();
    if(errcode==WAIT_FAILED) {
      ODINLOG(odinlog,errorLog) << lasterr() << STD_endl;
      return false;
    }
  }
#endif
  return true;
}

int Thread::self() {
  Log<ThreadComponent> odinlog("Thread","self");
  int result=-1; // the master thread gets this id
#ifdef USE_PTHREADS
  pthread_t ptself=pthread_self();
  pthreadindexmutex.lock();
  for(STD_map<int,pthread_t>::const_iterator it=pthreadindexmap.begin(); it!=pthreadindexmap.end(); ++it) {
    if(pthread_equal(ptself, it->second)) result=it->first;
  }
  pthreadindexmutex.unlock();
#endif
#ifdef USE_WINTHREADS
  result=GetCurrentThreadId();
#endif
  return result;
}




////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

#ifndef NO_UNIT_TEST

#include "tjvector.h"

#define VECSIZE 256
#define NITER 10000
#define NTHREADS 16

class TestThread : public Thread {

 public:

  void init(int* v, Mutex* m) {
    vec=v;
    mutex=m;
  }


 protected:

  void run() {
    for(int i=0; i<NITER; i++) {
      MutexLock lock1(*mutex);
      MutexLock lock2(*mutex); // testing recursive mutex
      for(int ivec=0; ivec<VECSIZE; ivec++) {
        vec[ivec]++;
      }
    }
  }


 private:
  int* vec;
  Mutex* mutex;

};


//////////////////////////////////////////////

class TestEventThread1 : public Thread {

 public:

  void init(double* r, Event* e, int d) {
    res=r;
    event=e;
    delay=d;
  }


 protected:

  void run() {
    sleep_ms(delay);
    (*res)=0.0;
    for(int i=0; i<NITER; i++) {
      (*res)+=sqrt(sqrt(double(i)));
    }
    event->signal();
  }


 private:
  double* res;
  Event* event;
  int delay;

};

//////////////////////////////////////////////

class TestEventThread2 : public Thread {

 public:

  void init(double* r, Event* e, int d) {
    res=r;
    event=e;
    delay=d;
  }


 protected:

  void run() {
    sleep_ms(delay);
    (*res)=123.4;
    event->wait();
  }


 private:
  double* res;
  Event* event;
  int delay;

};

//////////////////////////////////////////////

class ThreadedLoopTest : public ThreadedLoop<STD_string,STD_string,int> {

 private:
  bool kernel(const STD_string& in, STD_string& out, int&, unsigned int begin, unsigned int end) {
    out="";
    for(unsigned int i=begin; i<end; i++) {
      out+=in;
    }
    return true;
  }

};

//////////////////////////////////////////////


class ThreadTest : public UnitTest {

 public:
  ThreadTest() : UnitTest(ThreadComponent::get_compName()) {}

 private:

  bool check() const {
    Log<UnitTest> odinlog(this,"check");

    ///////////////////////////////////
    // Testing Thread / MutexLock

    TestThread thread[NTHREADS];

    Mutex mutex;

    int vec[VECSIZE];
    for(int ivec=0; ivec<VECSIZE; ivec++) vec[ivec]=0;

    int i,j;
    for(i=0; i<NTHREADS; i++) thread[i].init(vec,&mutex);
    for(i=0; i<NTHREADS; i++) thread[i].start();
    for(i=0; i<NTHREADS; i++) thread[i].wait();

    ivector iv(vec, VECSIZE);
    if( iv.minvalue()!=NITER*NTHREADS || iv.maxvalue()!=NITER*NTHREADS ) {
      ODINLOG(odinlog,errorLog) << "Mutex failed, iv=" << iv.printbody() << STD_endl;
      return false;
    }


    ///////////////////////////////////
    // Testing Event

    TestEventThread1 eventthread1[NTHREADS];
    Event event[NTHREADS];
    double res[NTHREADS];

    // Testing recycling of events / events with variable delay
    for(j=0; j<10; j++) {
      for(i=0; i<NTHREADS; i++) eventthread1[i].init(res+i,event+i,j); // with variable delays
      for(i=0; i<NTHREADS; i++) event[i].reset();
      for(i=0; i<NTHREADS; i++) eventthread1[i].start();
      sleep_ms(2);
      for(i=0; i<NTHREADS; i++) {

        event[i].wait();
        double expected=79994.7;
        if( fabs(res[i]-expected)>0.1 ) {
          ODINLOG(odinlog,errorLog) << "Event1 failed, res[" << i<< "]=" << res[i] << STD_endl;
          return false;
        }
      }
      for(i=0; i<NTHREADS; i++) eventthread1[i].wait();
    }


    // Testing multiple threads waiting on one signal
    TestEventThread2 eventthread2[NTHREADS];
    Event event2;
    for(j=0; j<10; j++) {
      for(i=0; i<NTHREADS; i++) eventthread2[i].init(res+i,&event2,j); // with variable delays
      for(i=0; i<NTHREADS; i++) eventthread2[i].start();

      ODINLOG(odinlog,normalDebug) << "[" << j << "] threads started" << STD_endl;

      sleep_ms(2);
      event2.signal();
      ODINLOG(odinlog,normalDebug) << "[" << j << "] signal sent" << STD_endl;

      for(i=0; i<NTHREADS; i++) {
        eventthread2[i].wait();
        double expected=123.4;
        if( res[i]!=expected ) {
          ODINLOG(odinlog,errorLog) << "Event2 failed, res[" << i<< "]=" << res[i] << STD_endl;
          return false;
        }
      }
    }




    ///////////////////////////////////
    // Testing Event


    unsigned int testsize=43536;

    for(unsigned int nthreads=1; nthreads<100; nthreads+=33) {

      ThreadedLoopTest tlt;
      tlt.init(nthreads, testsize);

      svector outvec;
      tlt.execute("T", outvec);

      STD_string result;
      for(unsigned int i=0; i<outvec.size(); i++) {
        result+=outvec[i];
      }
      if(result.length()!=testsize) {
        ODINLOG(odinlog,errorLog) << "result/testsize(" << nthreads << ")=" << result.length() << "/" << testsize << STD_endl;
        return false;
      }


      tlt.execute("N", outvec);

      result="";
      for(unsigned int i=0; i<outvec.size(); i++) {
        result+=outvec[i];
      }
      if(result.length()!=testsize) {
        ODINLOG(odinlog,errorLog) << "result/testsize(" << nthreads << ")=" << result.length() << "/" << testsize << STD_endl;
        return false;
      }
   }


    return true;
  }

};


void alloc_ThreadTest() {new ThreadTest();} // create test instance
#endif