forest-net
an overlay networks for large-scale virtual worlds
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator
pthreadExample.cpp
1 // Basic thread performance test
2 // Two threads alternate incrementing a counter up to a limit.
3 // On my Mac (2.6 GHz Intel Core i7) the average time per loop
4 // iteration (with a lock and an unlock) is 44 ns.
5 // So to keep lock overhead small, do no more than a million/sec.
6 
7 #include "Misc.h"
8 
9 int lockCount = 0;
10 pthread_mutex_t clok;
11 
12 using namespace forest;
13 
14 void* f(void* start) {
15  int i = *((int *) start);
16  while (i < 10000000) {
17  pthread_mutex_lock(&clok);
18  if (lockCount != i) { pthread_mutex_unlock(&clok); continue; }
19  lockCount++; i += 2;
20  pthread_mutex_unlock(&clok);
21  }
22 }
23 
24 int zero = 0;
25 int one = 1;
26 
27 int main() {
28  int startTime = Misc::getTime();
29 
30  pthread_t t0, t1;
31  pthread_create(&t0,NULL,f,(void *) &zero);
32  pthread_create(&t1,NULL,f,(void *) &one);
33 
34  pthread_join(t0,NULL); pthread_join(t1,NULL);
35  cout << Misc::getTime() - startTime << endl;
36 }