root/threadman/trunk/tests/test_cases.cpp

Revision 687, 2.2 kB (checked in by tapted, 2 years ago)

Implement asynchronous threads via Runners

  • Property svn:eol-style set to native
  • Property svn:keywords set to author date id revision url Rev Revision
Line 
1#include "threadman.h"
2#include <iostream>
3#include <sstream>
4
5using namespace std;
6
7static int serial = 0;
8struct Data {
9    Data* source;
10    int id;
11    Data(int i) : source(0), id(i) {
12        source = this;
13    }
14    Data(void* d) : source(static_cast<Data*>(d)), id(source ? source->id : 0) {}
15    int dump(const char* func = "?") {
16        ostringstream oss;
17        oss << func << " (in #" << ThreadMan::thread_id() << "): " << id << "\n";
18        if (source)
19            delete source;
20        // do it all at once to minimise chance of mixing thread output
21        cout << oss.str();
22        return 0;
23    }
24    static Data* x(int i = ++serial) {
25        return new Data(i);
26    }
27    int intmemfun() {
28        return dump(__func__);
29    }
30    bool boolmemfun() {
31        return dump(__func__);
32    }
33    //functors..
34    bool operator==(const Data& rhs) const {
35        /* for functors, things with the same serial will be synchronised */
36        return id == rhs.id;
37    }
38    int operator()() {
39        source = 0; /* this comes via temporary */
40        return dump(__func__);
41    }
42    int operator()(Data* d) {
43        source = 0; /* this comes via temporary */
44        d->dump("operator()+arg");
45        return dump("operator()+arg");
46    }
47};
48
49int oldschool(void* d) {
50    Data(d).dump(__func__);
51}
52
53long neater(Data* d) {
54    d->dump(__func__);
55}
56
57long noarg() {
58    Data::x()->dump(__func__);
59}
60
61void dotests(bool sync) {
62    ThreadMan &tm = ThreadMan::tman();
63
64    cout << "\n== Doing " << (sync ? "synchronised" : "concurrent") << " tests ==" << endl;
65
66    tm.run(oldschool, Data::x(), sync);
67
68    tm.run(ThreadMan::runner(oldschool), Data::x(), sync);
69    tm.run(ThreadMan::runner(neater), Data::x(), sync);
70    tm.run(ThreadMan::runner(noarg), 0, sync);
71
72    //member functions
73    tm.run(ThreadMan::runner(&Data::intmemfun), Data::x(), sync);
74    tm.run(ThreadMan::runner(&Data::boolmemfun), Data::x(), sync);
75
76    //functors
77    tm.run(ThreadMan::runner(Data(++serial)), 0, sync);
78    tm.run(ThreadMan::runner1<Data>(Data(++serial)), Data::x(), sync);
79
80}
81
82int main() {
83    ThreadMan &tm = ThreadMan::tman();
84    dotests(true);
85    tm.joinSync();
86    dotests(false);
87    tm.stopAsync();
88
89    return 0;
90}
Note: See TracBrowser for help on using the browser.