Please pardon the mouthful of a title, I couldn’t think of anything shorter.
I’m trying to create a class that has an std::queue
variable attached to it, and some methods. One method pushes values to the queue, one method enters a while
loop and performs actions based on the contents of the queue, one method is a static method that takes a pointer to an instance of the object as an argument and calls the aforementioned looping method of that instance, and one is a method that starts a thread with the previous method as a callback and this
as an argument.
At the crux of it, what I’m trying to do is this: have an object with a method that changes the value of a variable, and another method running in a different thread that reacts to that change and does something (in this case, access/pop the front element of the queue and do stuff with it)
My problem is that the method running in a different thread doesn’t seem to be able to register changes to the queue, and thus always thinks the queue is empty. I’ve managed to reproduce the problem in a sample project, where the queue is replaced by a simple boolean. If it were working properly, the asynchronous method would notice when the variable changes and color the screen green, but it does not. How should I go about fixing this? I’m somewhat new to the more advanced features of c++
, so go easy on me. I’m sure there’s a silly error that I’ve made somewhere in here.
Sample Project that Reproduces Error
robot-config.h
[default code that appears when project is created]
vex.h
[default code snipped]
//
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "v5.h"
#include "v5_vcs.h"
#include "foo.h"
#include "robot-config.h"
[default code snipped]
foo.h
#ifndef FOO_H
#define FOO_H
#include "robot-config.h"
class foo {
private:
static int callback(void *arg) {
if (arg == NULL) {return 0;}
foo *instance = static_cast<foo *>(arg);
instance->watch_variable();
}
void watch_variable() {
while (true) {
if (variable) {Brain.Screen.clearScreen(green);}
else {Brain.Screen.clearScreen(red);}
}
}
public:
bool variable = false;
void setvar() {
variable = true;
}
void start_watching() {
task watcher = task(foo::callback, static_cast<void *>(this));
}
};
#endif
main.cpp
[comments snipped]
// ---- START VEXCODE CONFIGURED DEVICES ----
// ---- END VEXCODE CONFIGURED DEVICES ----
#include "vex.h"
using namespace vex;
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
foo f = foo();
f.start_watching(); //start watching the variable
f.setvar(); //set the variable to true
//the variable watcher should register the variable being set to true and color the screen green,
//but it does not.
}
robot-config.cpp
[default code]