What is Qt for boost::promise<T>? - c++

I see that Qt has future class that is direct analog for boost::future but what is qt for boost::promise?

Constructing my own QFuture as shown in the accepted answer did not work for me. At first it seemed like it was working, but in my testing I realized it was not blocking the caller. Whoops! So I dug into the code a little further and found that QFutureInterface is what you want to use as your 'promise'. Like boost::promise, QFutureInterface is what you interact with in your worker thread, and it is a factory for QFutures.
So here's what I've been doing in Qt 4.8 (not sure if this is applicable to later versions).
QFutureInterface<QVariant> promise;
promise.reportStarted();
...
promise.reportResult(someVariant);
promise.reportFinished();
Then in the client thread, assuming you have access to the QFutureInterface 'promise'
QVariant result = promise.future().result();
The future() call is a factory method for creating a QFuture bound to your QFutureInterface. You should be able to get the QFuture and call result() on it later if you wanted.

The boost::promises are means of setting values in futures. In Qt, you can't set futures, you can only return them. That's the only way of "setting" data in a future.
So, in order to set data on a future, you have to return it from a function that was invoked by QtConcurrent::run. To do this, you'd use any of Qt's mechanisms for communicating between threads -- events, mutex-protected variables, etc. You have to tell the thread that runs the code that would return a future that given future is to be returned. That's the only way of achieving what a promise would do.
Alas, if you want to go into the undocumented territory, then the following code does what boost::promise::setValue would:
QFuture<int> f;
int i = 1;
...
f.d.reportResult(&i);
// or
f.d.reportFinished(&i);
I haven't bothered checking if it works (yet).

There is no official Qt analog but there are a few community libraries implementing promises (or similar patterns):
Ben Lau's AsyncFuture (benlau/asyncfuture)
Based on the undocumented QFutureInterface mentioned in one of the other answers.
And it's not exactly a promise pattern but rather an observer pattern.
Benoit Walter's QtPromise (bwalter/qt-promise)
Partially based on Ben Lau's AsyncFuture.
Simon Brunel's QtPromise (simonbrunel/qtpromise)
My QtPromise (julrich/QtPromise)
Disclaimer: I'm the author.

Promises for Qt are now also available with QML/JavaScript btw: https://v-play.net/updates/release-2-18-1-javascript-promises-for-rest-services-tinder-swipe-material-cards-qml-qsortfilterproxymodel-qml-youtube-player
Here is some example code:
import VPlayApps 1.0
import QtQuick 2.0
App {
Component.onCompleted: {
var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = HttpRequest
.get("http://httpbin.org/get")
.then(function(resp) {
return resp.body;
});
var p4 = Promise.all([p1, p2, p3]);
p4.then(function(values) {
console.log(values[0]); // 3
console.log(values[1]); // 1337
console.log(values[2]); // resp.body
});
}
}

I created this library that is highly integrated with Qt and implements javascript-like promises:
https://github.com/juangburgos/QDeferred
It allows to create a thread-safe async API as follows:
multiplyNumbersInThread(3, 4)
.fail([](int res) {
Q_UNUSED(res);
qDebug() << "multiplyPositiveNumbers failed!";
})
.done([](int res) {
qDebug() << "multiplyPositiveNumbers succeded! Result :" << res;
});
Hope you find it useful.

Related

uwp: How download files when app is in suspended mode

There is queue with links of files to download. I'm trying find the way to continue downloading when application goes to suspend mode.
According to official microsoft documentation suitable class for this is BackgroundDownloader, but it's handles only one current downloading process. It looks wrong to call in loop CreateDownload() method for every link without waiting for the completion of previous links, isn't right?
More logical in my opinion is using in-process background task. I see it this way:
Implement Run(IBackgroundTaskInstance) method of interface IBackgroundTask (it should stay alive even when app is suspended, right?)
Using custom event transmit the queue to the implemented method
Inside Run(IBackgroundTaskInstance) method use BackgroundDownloader (by implementing the execution of one instance at a time)
But I'm stuck even with simple implementation for one file downloading. Bellow my Run(IBackgroundTaskInstance) method implementation:
void Task::DownloaderTask::Run(IBackgroundTaskInstance ^ taskInstance)
{
TaskDeferral = taskInstance->GetDeferral();
std::wstring filename = L"Pleiades_large.jpg";
Uri^ uri = ref new Uri(ref new Platform::String(L"https://upload.wikimedia.org/wikipedia/commons/4/4e/Pleiades_large.jpg"));
Concurrency::create_task(KnownFolders::GetFolderForUserAsync(nullptr, KnownFolderId::PicturesLibrary))
.then([this, filename, uri](StorageFolder^ picturesLibrary)
{
return picturesLibrary->CreateFileAsync(ref new Platform::String(filename.c_str()), CreationCollisionOption::GenerateUniqueName);
}).then([this, filename, uri](StorageFile^ destinationFile) {
BackgroundDownloader^ downloader = ref new BackgroundDownloader();
DownloadOperation^ download = downloader->CreateDownload(uri, destinationFile);
download->StartAsync();
}).then([this](Concurrency::task<void> previousTask)
{
try
{
previousTask.get();
TaskDeferral->Complete();
}
catch (Platform::Exception^ ex)
{
wchar_t buffer[1024];
swprintf_s(buffer, L"Exception: %s", ex->Message);
OutputDebugString(buffer);
}
});
}
The code above only creates empty file, but using the same code without BackgroundTask it works correctly. I didn't find any restrictions for BackgroundDownloader inside BackgroundTask.
So, my questions are:
Is it right way of usage BackgroundTask?
Is there another approach to solving the problem?
Is this problem solvable at all?
I've found the cause of the unexpected behavior:
The line of code TaskDeferral->Complete(); was at the end of the method at first while it should be at the end of async call.
Therefore, initial implementation (published in question) is correct.
All that had to be done was to Rebuild project.

How to test asynchronuous code

I've written my own access layer to a game engine. There is a GameLoop which gets called every frame which lets me process my own code. I'm able to do specific things and to check if these things happened. In a very basic way it could look like this:
void cycle()
{
//set a specific value
Engine::setText("Hello World");
//read the value
std::string text = Engine::getText();
}
I want to test if my Engine-layer is working by writing automated tests. I have some experience in using the Boost Unittest Framework for simple comparison tests like this.
The problem is, that some things I want the engine to do are just processed after the call to cycle(). So calling Engine::getText() directly after Engine::setText(...) would return an empty string. If I would wait until the next call of cycle() the right value would be returned.
I now am wondering how I should write my tests if it is not possible to process them in the same cycle. Are there any best practices? Is it possible to use the "traditional testing" approach given by Boost Unittest Framework in such an environment? Are there perhaps other frameworks aimed at such a specialised case?
I'm using C++ for everything here, but I could imagine that there are answers unrelated to the programming language.
UPDATE:
It is not possible to access the Engine outside of cycle()
In your example above, std::string text = Engine::getText(); is the code you want to remember from one cycle but execute in the next. You can save it for later execution. For example - using C++11 you could use a lambda to wrap the test into a simple function specified inline.
There are two options with you:
If the library that you have can be used synchronously or using c++11 futures like facility (which can indicate the readyness of the result) then in your test case you can do something as below
void testcycle()
{
//set a specific value
Engine::setText("Hello World");
while (!Engine::isResultReady());
//read the value
assert(Engine::getText() == "WHATEVERVALUEYOUEXPECT");
}
If you dont have the above the best you can do have a timeout (this is not a good option though because you may have spurious failures):
void testcycle()
{
//set a specific value
Engine::setText("Hello World");
while (Engine::getText() != "WHATEVERVALUEYOUEXPECT") {
wait(1 millisec);
if (total_wait_time > 1 sec) // you can put whatever max time
assert(0);
}
}

Delaying a function call on OS X

I've seen there is a sleep method in the Win32 API and also a timer class to delay function calls.
Is there something similar that I can use on Mac OS?
I want a simple solution to create some sort of setTimeout function found in JavaScript and AS3.
You may do it using 2 methods:
1) Use NSObject's performSelector:withObject:afterDelay:
2) Use Grand Central Dispatch, like this:
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, interval * NSEC_PER_SEC);
dispatch_after(delay, dispatch_get_main_queue(), ^{
your code here
});
Or, for shorter syntax, you may add the following functions somewhere to your project:
void Dispatch_AfterDelay(dispatch_queue_t queue, NSTimeInterval afterInterval, dispatch_block_t block)
{
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, afterInterval * NSEC_PER_SEC);
dispatch_after(delay, queue, block);
}
void Dispatch_AfterDelay_ToMainThread(NSTimeInterval afterInterval, dispatch_block_t block)
{
Dispatch_AfterDelay(dispatch_get_main_queue(), afterInterval, block);
}
And then you just call:
Dispatch_AfterDelay_ToMainThread(5.0, ^{
your code
});
CFTimer actually exists in Core Foundation, which is C++ & C compatible.
It's not very well documented at all, from what I can tell. Here is a related question that mentions it.
On a higher level, there's also the standard C call of sleep (I've linked the man page for you here), and if you want to do this as a setTimeout type of function you could figure out a way to do sleep from a separate thread and then when it finishes (without being killed), consider things "timed out".
You can do that with an NSTimer.
If you can write a C function (or a block) to wrap your C++ code, then you can use Grand Central Dispatch.
Look at dispatch_after_f for a delayed call of a function or dispatch_after for its block based equivalent.
You can look at Unix calls like sleep() and poll().

problem of callback from C++ to JS

I'm a newer to NPAPI. I come across one problem.
in my plugin, I need to return some data from C++ to JavaScript, yes,that's callback. but the callback thread and the main thread are separate threads. So I use NPN_PluginThreadAsyncCall, but the problem can not be solved also. When callback, the firefox crashed...
Can anyone help me?
the bellow codes are in the callback thread, Can anyone tell me, why it crashed?
npnfuncs->pluginthreadasynccall(instance,callBackfunc,(void*)pdata);
/////////////////////////////////////////////////////////////////////
void callBackfunc(void* arg)
{
NPObject *winobj;
npnfuncs->getvalue(instance,NPNVWindowNPObject,&winobj);
NPVariant handler;
NPIdentifier id1 = npnfuncs->getstringidentifier("MyTest".c_str());
npnfuncs->getproperty(instance, winobj, id1, &handler);
NPObject* handlerObj= NPVARIANT_TO_OBJECT(handler);
NPVariant prototype;
NPIdentifier id2 = npnfuncs->getstringidentifier("prototype");
npnfuncs->getproperty(instance, serviceHandlerObj, id2, &prototype);
NPObject* prototypeObj= NPVARIANT_TO_OBJECT(prototype);
NPIdentifier id = npnfuncs->getstringidentifier("fun".c_str());
NPVariant voidResponse;
int status=npnfuncs->invoke(instance,prototypeObj,id,args,argCount,&voidResponse);
return;
}
thanks
Best Regards
greatsea
... What is "MyTest".c_str() supposed to be? This is C++, no? c_str() is a method of a std::string class, and I don't see that being sued here, so trying to do a .c_str() on it shouldn't even compile, unless there is something going on here that I really don't understand.
Also be aware that at least Safari 5.1 has stopped supporting NPN_PluginThreadAsyncCall and different methods need to be used to make cross-thread callbacks. I don't know if other browsers have or will or not; so far it doesn't seem so.
Is there a reason you're not just using FireBreath for your plugin? It solves all of these problems for you and lets you just focus on your plugin...

Aspect Oriented Programming in Qt

I'm trying to get my head around AOP and some Qt Code would really help.
From wikipedia here is some sample code (easy for a Qt/C++ programmer to read):
void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger)
throws Exception {
logger.info("transferring money...");
if (! checkUserPermission(user)){
logger.info("User has no permission.");
throw new UnauthorizedUserException();
}
if (fromAcc.getBalance() < amount) {
logger.info("Insufficient Funds, sorry :( ");
throw new InsufficientFundsException();
}
fromAcc.withdraw(amount);
toAcc.deposit(amount);
//get database connection
//save transactions
logger.info("Successful transaction. :) ");
}
And then "aspectized":
void transfer(Account fromAcc, Account toAcc, int amount) throws Exception {
if (fromAcc.getBalance() < amount) {
throw new InsufficientFundsException();
}
fromAcc.withdraw(amount);
toAcc.deposit(amount);
}
aspect Logger
{
void Bank.transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger)
{
logger.info("transferring money...");
}
void Bank.getMoneyBack(User user, int transactionId, Logger logger)
{
logger.info("User requested money back");
}
// other crosscutting code...
}
Qt has signals and slots to decouple objects. But I still need to emit signals.
So: Can this be done with Qt or do I need some special framework/preprocessors as referenced in the wikipedia article?
I have a feeling that there must be some trick since Qt uses the Meta Object Compiler and some functionality might be "injected" with dynamic methods.... just spit-balling here ;)
Edit: To give a better context: I really like the dynamic aspects (power) of the Qt meta object with signals and slots and would like to keep a Qt feel to it. Thus, my idea is to make use of slots (or signals) as point cuts. For example:
If I define slot Bank::transfer(...) and then signal Bank::OnBeforeTranfer() and signal Bank::OnAfterTransfer(). If I then connect them to other aspects say Security::transfer() and Logger::transfer() (all QObjects) I can block calls (like fail OnBeforeTransfer).
But, if we then take it to the next evolution to get less and cleaner code I would like to get rid of the OnXXXX signals and connect the Bank::transfer slot to Security::transfer slot and Logger::transfer. Anything dynamic in Qt? : Like order of calling slots and and preventing next call in the "slot chain"?
This whole context can still be considered AOP right? I'm trying to stick to "method level point cuts" or am I totally beside the point here?
In what language are you planning to use Qt? I recently had to build a simple GUI in Qt around a python script and used the AOP python package Aspyct to do some quick before and after stuff. Qt is event-driven programming, I'd say get familiar with the Qt basics, many things are similar to AOP-style operations and then find some AOP libraries for the language you plan to use Qt in.
Another AOP framework you may consider using is AspectC++. I've played with it a bit and it seems to work quite well. They even have a whitepaper on the site that describes how AspectC++ can be used with Qt.
If you want to stay within the Qt framework, you could take a look at the State Machine Framework. (And get rid of the exceptions :)
Then you could just connect the Logger to state change events.