For simplicity the thread here is just a plain function.
#include <iostream>
class C {
public:
C(int* value) : value_(value) {}
void f();
private:
int* value_;
};
void C::f() {
// threadsafe_begin
int val = *value_;
// threadsafe_end
if(val) {
// do something useful...
std::cout << val;
}
}
void thread(int* value) {
// threadsafe_begin
*value = 123;
// threadsafe_end
}
int main() {
int* val = new int(0);
C aC(val);
thread(val);
aC.f();
return 0;
}
Something like the following quick pseudo-code:
______________________________________________________________________
void worker_threads();
class future {
HANDLE m_event; // manual-reset event set to false
virtual void compute() = 0;
void prv_complete() {
compute();
SetEvent(m_event);
}
friend void worker_threads();
public:
void wait() {
WaitForSingleObject(m_event, INFINITE);
}
};
static thread_safe_queue<future*> g_future_queue;
void worker_threads() {
for (;;) {
g_future_queue.pop_wait()->prv_complete();
}
}
void foo() {
class computation : public future {
int m_value;
void compute() {
// lengthy processing
m_value = 123;
}
void whatever() {
g_future_queue.push(this);
wait();
// `m_value' is now ready
}
};
computation c;
c.whatever();
}
______________________________________________________________________
?
Should probably just use an automatic reset event here. Unless you want to
allow multiple threads to wait on a single future. However, then some "reset
event logic" would need to be implemented. I would advise you to just use
the automatic event, and only allow a single thread to wait on a future
object...
> [...]
> ______________________________________________________________________