-
-
Notifications
You must be signed in to change notification settings - Fork 52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
like winrt #201
Comments
Hi, we already support something like this, although it's not so succinct as WinRt and it doesn't use thread pool - there's QCoro::Task<> DoWorkAsync(QLabel *label)
{
// capture current thread
auto *uiThread = QThread::currentThread();
// prepare worker thread
QThread workerThread;
workerThread.start();
// we are still on UI thread, so we can interact with the UI
label->setText("Working...");
// switch current thread context to the worker thread
co_await QCoro::movetoThread(&workerThread);
// ...
// do your work here running on the workerThread
// ...
// switch thread context back to the ui thread
co_await QCoro::moveToThread(uiThread);
// back on the main thread, we can interact with UI agin.
label->setText("Done");
// stop the worker thread, we don't need it anymore
workerThread.quit();
workerThread.wait();
} Managing the worker thread could be hidden into a RAII class, something like the code below, although I'm not sure whether that's something that belongs to QCoro. class WorkerThread {
public:
explicit WorkerThread()
: mThread(new QThread())
{
mThread->start();
}
QThread *thread() const { return mThread; }
~WorkerThread()
{
// NOTE: this needs a much more careful approach to avoid leaks, this code is just for example
if (mThread->isRunning()) {
connect(mThread, &QThread::finished, mThread, &QObject::deleteLater);
mThread->quit();
} else {
mThread->deleteLater();
}
}
private:
QThread *mThread = nullptr;
}; That makes the code much nicer: QCoro::Task<> DoWorkAsync(QLabel *label)
{
auto *uiThread = QThread::currentThread();
WorkerThread workerThread;
label->setText("Working...");
co_await QCoro::movetoThread(workerThread.thread());
// do your work here running on the workerThread
co_await QCoro::moveToThread(uiThread);
label->setText("Done");
} It should even be possible to craft integration with QThreadPool so that one does not have to create the worker thread manually and get some throttling on the number of background tasks. But same as with But there's also been requests for SQL integration (#188), I've been thinking about native async file IO classes and here you are with those threading primitives, so I'll have to re-consider the scope or create a QCoroExtras library.... |
This looks pretty good already |
https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/concurrency-2
Do you consider supporting thread pools to support computational tasks
The text was updated successfully, but these errors were encountered: