I"m not sure what the goal is at this point, but here is an example with pause and continue from main():
Code:
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
struct test
{
double x[10], y[10];
double *cxpx = &x[0]; // ptrs for change_x
double *cxpy = &y[0];
double *pxpx = &x[0]; // ptrs for print_x
double *pxpy = &y[0];
std::atomic<bool> stop = false;
std::atomic<bool> pause = false;
};
class handle_Event
{
private:
bool signalled;
std::condition_variable_any c_v;
std::mutex mtx;
public:
handle_Event()
{
signalled = false;
}
~handle_Event()
{
}
void signal(void)
{
std::lock_guard<std::mutex> lck(mtx);
signalled = true;
c_v.notify_one();
}
void reset(void)
{
std::lock_guard<std::mutex> lck(mtx);
signalled = false;
}
bool wait(void)
{
std::lock_guard<std::mutex> lck(mtx);
while (!signalled)
c_v.wait(mtx);
return signalled;
}
};
handle_Event hndl_change_x, hndl_print_x, hndl_continue;
void change_x(test &t)
{
while (1){
hndl_change_x.wait(); // wait
hndl_change_x.reset();
if (t.stop.load()) // exit if stop flag set
break;
const double f = t.cxpx[0];
for (uint16_t i = 0; i < 10; i++)
t.cxpy[i] = ((i + 1) % 10) ? t.cxpx[i + 1] : f;
std::swap(t.cxpx, t.cxpy);
hndl_print_x.signal(); // ready for print
}
}
void print_x(test &t)
{
while (1){
hndl_print_x.wait(); // wait
hndl_print_x.reset();
if (t.pause.load()){ // pause if pause set
hndl_continue.wait();
hndl_continue.reset();
}
if (t.stop.load()) // exit if stop flag set
break;
hndl_change_x.signal(); // ready for change
for (uint16_t j = 0; j < 10; j++)
std::cout << t.pxpx[j] << " ";
std::cout << std::endl;
std::swap(t.pxpx, t.pxpy);
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
int main(void)
{
double x0[] = { 0., 1., 2., 3., 4., 5., 6., 7., 8., 9. };
test var;
for (uint16_t i = 0; i < 10; i++) var.x[i] = x0[i];
char hit = 0;
std::thread thread_change_x(change_x, std::ref(var));
std::thread thread_print_x(print_x, std::ref(var));
hndl_print_x.signal(); // start with print
while (1){ // wait for input
if ((hit = std::cin.get()) == 'x')
break;
if ((hit == 'p') && (var.pause.load() == false))
var.pause.store(true);
if ((hit == 'c') && (var.pause.load() == true)){
var.pause.store(false);
hndl_continue.signal();
}
}
var.stop.store(true); // stop threads
hndl_change_x.signal();
hndl_print_x.signal();
hndl_continue.signal();
thread_change_x.join(); // wait for child threads to stop
thread_print_x.join();
return 0;
}