2

I have a program with a QThread, which contains a network client. The client is supposed to take an object, process it, upload it to a server, get the response, and report back to the main thread. I did this with std::promise, and used its future. I made std::promise a member of the object emitted after having taken its future.

A minimal sample code is the following:

The object I'm emitting:

struct FileToUpload
{
    std::string fileData;
    std::string filename;
    std::promise<int> promise;
}

The part I'm using for emitting:

FileToUpload theFile;
auto uploadFuture = theFile.promise.get_future();
emit uploadFile(&theFile); //passing pointer because promise is non-copyable
auto uploadSuccess = uploadFuture.get();

Is there a Qt way to do the same?

I only found a QFuture class that can be used with QtConcurrent. I couldn't find a single example that explains how to use this with QThread. What are my options to do this with Qt correctly?

The Quantum Physicist
  • 24,987
  • 19
  • 103
  • 189
  • Do you *need* to move to `QFuture`? Also, is the `FileToUpload` structure under your control -- i.e. can you modify its definition? – G.M. Mar 29 '17 at 10:00
  • @G.M. Actually I have the full freedom whether I have to move the future or not (though I prefer not to have to copy it... it's a file eventually with a few MBs of size; also "Qt metatypes" has a problem with non-copyable stuff, so I saved myself the trouble by passing pointers). I also have full freedom on how `FileToUpload` looks like. What I need to achieve is simply the model where I pass the file to the thread, and wait for the client thread to be done through the future. I created that promise as a way to do it, and it can be changed as necessary. – The Quantum Physicist Mar 29 '17 at 10:06

1 Answers1

2

yes, you may use QFuture without QConcurrent. But the API is not documented. You may take a look with my wrapper library, AsyncFuture, at:

https://github.com/benlau/asyncfuture

It has a clear example to use QFuture like a promise object.

benlau
  • 301
  • 3
  • 9