void Callback (XPointer, XRecordInterceptData *pRecord) { std::cout << "my logs\n"; }
int main ()
{
if(auto* const pDisplay = XOpenDisplay(nullptr))
{
XRecordClientSpec clients = XRecordAllClients;
auto* pRange = ::XRecordAllocRange();
pRange->device_events = XRecordRange8{KeyPress, ButtonRelease};
auto context = ::XRecordCreateContext(pDisplay, 0, &clients, 1, &pRange, 1);
::XRecordEnableContextAsync(pDisplay, context, Callback, nullptr); // use with/without `...Async()`
::XRecordDisableContext(pDisplay, context);
::XRecordFreeContext(pDisplay, context);
::XFree(pRange);
::XFlush(pDisplay);
::XSync(pDisplay, true);
}
}
I am noticing that even after XRecordDisableContext(), the Callback() continues to be invoked.
How can we disable the recording, so that the callback isn't invoked anymore?
Note:
Have taken example from this site.
Don't know how to use XRecordEnableContext(), so using XRecordEnableContextAsync(). Is that the source of problem?
One way is to move below statement into the Callback() or some equivalent other thread. For testing purpose, I changed the code as below where after few event raised, I disable from the Callback() and it works.
::Display* pDisplay;
XRecordRange* pRange;
XRecordContext context;
#define CHECK(EVENT) if(*pDatum == EVENT) qDebug() << #EVENT
void Handle (XPointer, XRecordInterceptData *pRecord)
{
std::cout << "my logs\n";
static int i = 0;
if(++i < 10)
return;
::XRecordDisableContext(pDisplay, context);
::XRecordFreeContext(pDisplay, context);
::XFree(pRange);
::XFlush(pDisplay);
::XSync(pDisplay, true);
}
// other code same, except 3 variables are global and "Free"-up functions are not required
Related
I am writing unit tests for one of the classes I want to test. Function infFooLoop() what I want to test is executed in endless loop (request to stop it comes externally). My problem is I want to change the private variable state_ via setter in setState when function executes in separate thread asynchronously. Some simplified code example is here:
enum class State : int
{
Success = 1,
Failure = 2
};
class Foo
{
private:
State state_{State::Success};
bool stop_flag_{false};
public:
void setState(State state) { state_ = state; }
void infFooLoop(bool &start)
{
while (start)
{
std::cout << "While loop executes \n";
if (state_ == State::Failure)
{
stop_flag_ = true;
}
else if (stop_flag_)
{
std::cout << "Program stopped\n";
// Report error but for this example break
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
}
};
int main()
{
Foo obj;
bool flag{true};
std::future<void> future = std::async(std::launch::async, [&](){ obj.infFooLoop(flag);});
// Try to change the data:
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// I want to change data for `Failure` so stop_flag condition will be used
obj.setState(State::Failure);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
// terminate loop
flag = false;
return 0;
}
state_ will be taken from external component and stop_flag_ is used to handle some corner-case here (in real it wont break the loop, just report error to different component).
I assume infFooLoop executes on a separate thread so I can't just call another function in a different thread to change this data. stop_flag_ is some internal variable used only in this one function so I want to leave it as simple as possible (do not introduce mutexes/atomic in Foo class only for tests). Can you give me some suggestions on what should I do here?
I am storing js callbacks in vector:
std::vector<std::unique_ptr<Persistent<Function>>> callbacks;
Everything is working fine. The problem is that I do not want to store duplicated callbacks because I do not want to notify the same callback twice. I have to compare them somehow. Here is my full function but that does not work:
void ProcessCallback(const FunctionCallbackInfo<Value>& args)
{
std::string returnInfo;
Isolate* isolate = args.GetIsolate();
Local<Function> notifyFunction = Local<Function>::Cast(args[0]);
auto predicate = [&](const std::unique_ptr<Persistent<Function>>& c)
{
return c->Get(isolate)->StrictEquals(notifyFunction);
};
auto it = std::find_if(callbacks.begin(), callbacks.end(), predicate);
if (it == callbacks.end())
{
returnInfo = "Did not find callback. Adding..." + std::to_string(callbacks.size());
auto persistentCallback = std::make_unique<Persistent<Function>>(isolate, notifyFunction);
callbacks.emplace_back(std::move(persistentCallback));
}
else
{
returnInfo = "Callback already exist in a list.\n";
}
args.GetReturnValue().Set(String::NewFromUtf8(isolate, returnInfo.c_str()).ToLocalChecked());
}
In js:
function callback(msg) {
console.log(msg);
}
let addon = require('./build/Release/addon');
console.log(addon.on(callback));
console.log(addon.on(callback));
Is there something that I can rely on to uniquely identify function that is passed from js? Thanks.
Consider the following example that takes a msg and posts it asynchronously.
void sendMessage(std::string msg) {
runAsync<void>([msg = std::move(msg)] {
onPostMessage(cookie, msg.c_str());
});
};
Would the following be faster?
void sendMessage(std::string&& msg) {
What would be the best options at the calling site?
auto msg = ...
postMessage(msg);
or
auto msg = ...
postMessage(std::move(msg));
Note that msg isn't needed after the call anymore.
Will the compiler automatically detect that I am not using msg anymore after the call and "move" it?
I would use the following solution:
void sendMessage(std::string&& msg) {
runAsync<void>([msg = std::move(msg)] {
onPostMessage(cookie, msg.c_str());
});
};
and at the calling site:
auto msg = ...
sendMessage(std::exchange(msg, {}));
I want to have different OpenCV functions running with std::async()
As an example, I'm trying to acquire and display images using my webcam.
I did a class called camHandler to encapsulate this.
This example is made asynchronous on purpose, I know I could just display the image after acquiring it :)
I first use the open() function in a member cap:
auto camHandler::initCamera(int deviceID) -> camHandler::CamState {
this->deviceID = deviceID;
this->apiID = cv::CAP_ANY;
cap.open(deviceID, apiID);
if (!cap.isOpened()) {
this->currentState = error;
return this->currentState;
}
return Ready;
}
I have a function for acquisition and another one for displaying:
auto camHandler::imageStreaming() -> void{
this->currentState = streaming;
while(true)
{
std::cout << "Acc " << std::endl;
cap.read(this->frame);
this->acquired++;
if (this->frame.empty()) {
this->currentState = error;
break;
}
};
}
and
auto camHandler::displayImage() -> void {
while(true){
std::cout << "Disp " << std::endl;
cv::imshow("Live", this->frame);
this->displayed++;
if (cv::waitKey(5) >= 0){
this->currentState = paused;
break;
}
};
}
finally, I did a function that will call these 2 functions inside a std::async():
auto camHandler::startStreaming() -> void {
auto stream = std::async(&camHandler::imageStreaming, this);
auto disp = std::async(&camHandler::displayImage, this);
}
The problem
In my main I only call:
camHandler ch;
ch.initCamera();
ch.startStreaming();
And I get:
Acc Disp
Acc
Acc
Acc
Acc
Acc
Which means that display was only called once and acquisition kept running.
How can I make sure both are running?
Like this I don't even see the image window from OpenCV.
My camera and display work properly when I do the normal capturing as shown in OpenCV's Site
If you try to call cv::imshow with an empty cv::Mat, it will throw an exception, and async will end.
Since it's running in async, cv::imshow("Live", this->frame) can be called before cap.read(this->frame).
You should check cv::Mat is not empty before displaying.
The purpose of the following code is to have various classes publish data to an observable. Some classes will observe every data, some will observe periodically with buffer_with_time().
This works well until the program exits, then it crashes, probably because the observer using buffer_with_time() is still hanging on to some thread.
struct Data
{
Data() : _subscriber(_subject.get_subscriber()) { }
~Data() { _subscriber.on_completed(); }
void publish(std::string data) { _subscriber.on_next(data); }
rxcpp::observable<std::string> observable() { return _subject.get_observable(); }
private:
rxcpp::subjects::subject<std::string> _subject;
rxcpp::subscriber<std::string> _subscriber;
};
void foo()
{
Data data;
auto period = std::chrono::milliseconds(30);
auto s1 = data.observable()
.buffer_with_time(period , rxcpp::observe_on_new_thread())
.subscribe([](std::vector<std::string>& data)
{ std::cout << data.size() << std::endl; });
data.publish("test 1");
data.publish("test 2");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// hope to call something here so s1's thread can be joined.
// program crashes upon exit
}
I tried calling "s1.unsubscribe()", and various as_blocking(), from(), merge(), but still can't get the program to exit gracefully.
Note that I used "subjects" here because "publish" can then be called from different places (which can be from different threads). I am not sure if this is the best mechanism to do that, I am open to other ways to accomplish that.
Advice?
This is very close to working..
However, having the Data destructor complete the input while also wanting the subscription to block the exit of foo until input is completed makes this more complex.
Here is a way to ensure that foo blocks after Data destructs. This is using the existing Data contract.
void foo1()
{
rxcpp::observable<std::vector<std::string>> buffered;
{
Data data;
auto period = std::chrono::milliseconds(30);
buffered = data.observable()
.buffer_with_time(period , rxcpp::observe_on_new_thread())
.publish().ref_count();
buffered
.subscribe([](const std::vector<std::string>& data)
{ printf("%lu\n", data.size()); },
[](){printf("data complete\n");});
data.publish("test 1");
data.publish("test 2");
// hope to call something here so s1's thread can be joined.
// program crashes upon exit
}
buffered.as_blocking().subscribe();
printf("exit foo1\n");
}
Alternatively, the changing the shape of Data (add a complete method) would allow the following code:
struct Data
{
Data() : _subscriber(_subject.get_subscriber()) { }
~Data() { complete(); }
void publish(std::string data) { _subscriber.on_next(data); }
void complete() {_subscriber.on_completed();}
rxcpp::observable<std::string> observable() { return _subject.get_observable(); }
private:
rxcpp::subjects::subject<std::string> _subject;
rxcpp::subscriber<std::string> _subscriber;
};
void foo2()
{
printf("foo2\n");
Data data;
auto newthread = rxcpp::observe_on_new_thread();
auto period = std::chrono::milliseconds(30);
auto buffered = data.observable()
.buffer_with_time(period , newthread)
.tap([](const std::vector<std::string>& data)
{ printf("%lu\n", data.size()); },
[](){printf("data complete\n");});
auto emitter = rxcpp::sources::timer(std::chrono::milliseconds(0), newthread)
.tap([&](long) {
data.publish("test 1");
data.publish("test 2");
data.complete();
});
// hope to call something here so s1's thread can be joined.
// program crashes upon exit
buffered.combine_latest(newthread, emitter).as_blocking().subscribe();
printf("exit foo2\n");
}
I think that this better expresses the dependencies..