Skip to content

Instantly share code, notes, and snippets.

@darthsuogles
Last active November 24, 2016 21:45
Show Gist options
  • Select an option

  • Save darthsuogles/663589ee2d8f44c40802b0b731c9ea6f to your computer and use it in GitHub Desktop.

Select an option

Save darthsuogles/663589ee2d8f44c40802b0b731c9ea6f to your computer and use it in GitHub Desktop.
#include <thread>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cassert>
using namespace std;
void foncI(int m) {
int res = 0;
for (int i = 0; i < m; res += i++);
}
void foncR(float f) {
float res = 120.;
f = (f > 0.) ? f : (-f);
while (res > 0) res -= f;
}
vector<string> prog = {
"A",
"B",
"THREAD_BEGIN",
"C",
"A",
"B",
"THREAD_END",
"D",
"D",
"A",
"B"
};
class InterpState {
public:
string tag;
int lno;
string val;
string expr;
vector<thread> pool;
public:
InterpState(): tag("MAIN"), lno(0), val("VOID"), expr("INIT") { }
InterpState(int lno) {
this->tag = "THREAD";
this->lno = lno;
this->val = "VOID";
this->expr = "THREAD_INIT";
}
bool is_main() { return "MAIN" == this->tag; }
};
void interp(InterpState* state) {
assert(state != NULL);
for (int i = state->lno; i < prog.size(); ++i) {
string expr = prog[i];
state->lno = i;
if ("THREAD_BEGIN" == expr) {
state->pool.push_back(thread(interp, new InterpState(i+1)));
} else if ("THREAD_END" == expr) {
if (state->is_main()) {
for (auto it = state->pool.begin(); it != state->pool.end(); ++it)
it->join();
cout << "thread pool done: " << state->pool.size() << endl;
} else return;
} else {
state->expr = expr;
string val = expr;
transform(val.begin(), val.end(), val.begin(), ::tolower);
state->val = val;
printf("%8s: %32s => %32s\n", state->tag.c_str(), expr.c_str(), val.c_str());
}
}
}
int main(int argc, char** argv) {
thread t1(foncI, 10);
thread t2(foncR, 32.);
cout << "in the meantime" << endl;
t1.join(); t2.join();
cout << "threads finished" << endl;
interp(new InterpState);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment