Irc-Unix.net

Главная | Actual Topics | Обратная связь | Guest Book | В избранное | Сделать домашней
Категории
 System & Utilities
 Unix News
 OS Emulator
 Developing
 Learning/Education
 Games
 Humour
Каталог статей
Все статьи

Antispam
Статьи
Биллу Гейтсу тоже предлагают избавиться ...
Вымогательство в борьбе со спамом
Календарь

June, 2018
ПнВтСрЧтПтСбВс
123
45678910
11121314151617
18192021222324
252627282930
Опросы
Какой из этих ОС Вы отдаете большее предпочтение?

QNX
FreeBSD
Linux(any)
Solaris
Mac OS
Windows XP
Windows 2003
Что такое ОС? :)


Результаты
Другие опросы

Всего голосов: 326
Комментарии: 0
Ссылки

Архив Новостей
 June 2018 (6)
 May 2018 (10)
 April 2018 (14)
 March 2018 (11)
 February 2018 (13)
 January 2018 (13)
 December 2017 (14)
 November 2017 (15)
 October 2017 (19)
 September 2017 (18)
 August 2017 (13)
 February 2017 (14)
 January 2017 (19)
 December 2016 (16)
 November 2016 (16)
 October 2016 (21)
 September 2016 (18)
 August 2016 (16)
 July 2016 (16)
 June 2016 (20)
 May 2016 (18)
 April 2016 (15)
 March 2016 (22)
 February 2016 (17)
 January 2016 (15)
 December 2015 (15)
 November 2015 (22)
 October 2015 (20)
 September 2015 (17)
 August 2015 (25)
 July 2015 (20)
 June 2015 (23)
 May 2015 (21)
 April 2015 (17)
 March 2015 (19)
 February 2015 (9)
 January 2015 (23)
 December 2014 (9)
 November 2014 (13)
 October 2014 (12)
 September 2014 (18)
 August 2014 (20)
 July 2014 (10)
 June 2014 (12)
 May 2014 (12)
 April 2014 (10)
 March 2014 (22)
 February 2014 (10)
 January 2014 (8)
 December 2013 (26)
 November 2013 (53)
 October 2013 (40)
 September 2013 (48)
 August 2013 (63)
 July 2013 (56)
 June 2013 (52)
 May 2013 (49)
 April 2013 (67)
 March 2013 (74)
 February 2013 (63)
 January 2013 (62)
 December 2012 (62)
 November 2012 (66)
 October 2012 (68)
 September 2012 (48)
 August 2012 (75)
 July 2012 (60)
 June 2012 (71)
 May 2012 (69)
 April 2012 (85)
 March 2012 (86)
 February 2012 (90)
 January 2012 (81)
 December 2011 (103)
 November 2011 (118)
 October 2011 (74)
 September 2011 (2)
 June 2011 (110)
 May 2011 (118)
 April 2011 (111)
 March 2011 (112)
 February 2011 (101)
 January 2011 (119)
 December 2010 (117)
 November 2010 (118)
 October 2010 (131)
 September 2010 (117)
 August 2010 (226)
 July 2010 (351)
 June 2010 (305)
 May 2010 (319)
 April 2010 (343)
 March 2010 (329)
 February 2010 (311)
 January 2010 (312)
 December 2009 (266)
 November 2009 (156)
 July 2009 (101)
 June 2009 (279)
 May 2009 (365)
 April 2009 (348)
 March 2009 (347)
 February 2009 (323)
 January 2009 (318)
 December 2008 (237)
 November 2008 (155)
 October 2008 (334)
 September 2008 (310)
 August 2008 (343)
 July 2008 (362)
 June 2008 (322)
 May 2008 (514)
 April 2008 (1276)
 March 2008 (1658)
 February 2008 (250)
 January 2008 (6)
 November 2007 (1)
 September 2007 (1)
 June 2007 (1)
 May 2007 (1)
 March 2007 (1)
 January 2007 (2)
 December 2006 (1)
 October 2006 (2)
 September 2006 (1)
 August 2006 (2)

Playing with coroutines and Qt

System & Utilities

Hello!
I was recently wondering about the status of the coroutines in C++ and I found several implementations. I decided to choose this one for my experiment.
It’s simple and easy to use and works in Linux and Windows.

My goal was to try to find a way to have code running asynchronously without waiting for signals to trigger my slots and avoiding to call QCoreApplication::processEvents or creating a QEventLoop in the stack.

My first approach was to convert the processEvent function of a custom event dispatcher into a coroutine and use yield. After several failures, I decided not to continue this way.

My next attempt was to convert a slot into a coroutine:

QTimer::singleShot(0, std::bind(&coroutine::resume, coroutine::create([]() { ... });

Inside this lambda, the CPU will execute the code until the yield, it will jump back to the application event loop.
The full code is:

#include \"coroutine.h\"
#include <QtCore>
#include <QtWidgets>

int main(int argc, char **argv)
{
QApplication app(argc, argv);
QPushButton fibonacciButton(\"0: 0\");
fibonacciButton.show();
QObject::connect(&fibonacciButton, &QPushButton::pressed,
std::bind(&coroutine::resume, coroutine::create([&]() {
qulonglong f0 = 1, f1 = 0, n = 1;
fibonacciButton.setText(QString(\"1: 1\"));
coroutine::yield();
fibonacciButton.setText(QString(\"2: 1\"));
forever {
auto next = f1 + f0;
f0 = f1;
f1 = next;
fibonacciButton.setText(QString(\"%0: %1\").arg(n++).arg(f0 + f1));
coroutine::yield();
}
})));
return app.exec();
}

Here we can see a button connected to a lambda function which calculates the numbers in the Fibonacci sequence. After calculating the next number, we call yield and this will jump from this function to the event loop. When the user presses the button again, the code will return to the next line after the yield.

This example works because the user needs to press the button again to resume the execution of the code.

However, sometimes we want to resume the execution automatically. To do this, we need to yield the execution and schedule a resume of the execution:

void qYield()
{
const auto routine = coroutine::current();
QTimer::singleShot(0, std::bind(&coroutine::resume, routine));
coroutine::yield();
}

The first line gets the identifier of the coroutine and the second schedules the resume. With yield the CPU will come back to the previous frames and finally to the main loop with a resume enqueued resuming the code unconditionally.

Next step is to try to resume when a condition happens. Qt provides signals that indicate when something happened, so the more optimal way to yield the execution is:

template <typename Func>
void qAwait(const typename QtPrivate::FunctionPointer::Object *sender, Func signal)
{
const auto routine = coroutine::current();
const auto connection = QObject::connect(sender, signal,
std::bind(&coroutine::resume, routine));
coroutine::yield();
QObject::disconnect(connection);
}

Instead of enqueuing a resume we create a temporary connection to resume the execution of our slot.

An example of this can be:

#include \"coroutine.h\"
#include <QtCore>
#include <QtWidgets>
#include <QtNetwork>

int main(int argc, char **argv)
{
QApplication app(argc, argv);
QPlainTextEdit textEdit;
textEdit.show();
QTimer::singleShot(0, std::bind(&coroutine::resume, coroutine::create([&]() {
QUrl url(\"http://download.qt.io/online/qt5/linux/x64/online_repository/Updates.xml\");
QNetworkRequest request(url);
QNetworkAccessManager manager;
auto reply = manager.get(request);
qAwait(reply, &QNetworkReply::finished);
textEdit.setPlainText(reply->readAll());
reply->deleteLater();
})));
return app.exec();
}

Here, I created a QTextEdit which receives the content of a file from internet. When the QNetworkReply finishes, the data is written in the QTextEdit.

Another example:

#include \"coroutine.h\"
#include <QtCore>
#include <QtWidgets>
#include <QtNetwork>

int main(int argc, char **argv)
{
QApplication app(argc, argv);
QPlainTextEdit edit;
edit.show();

QTimer::singleShot(0, std::bind(&coroutine::resume, coroutine::create([&]() {
auto previousText = edit.toPlainText();
forever {
if (edit.toPlainText() == QStringLiteral(\"quit\")) {
qApp->quit();
} else if (previousText != edit.toPlainText()) {
qDebug() << previousText << \"->\" << edit.toPlainText();
previousText = edit.toPlainText();
}
qAwait(&edit, &QPlainTextEdit::textChanged);
qDebug() << \"QPlainTextEdit::textChanged\";
}
})));
return app.exec();
}

This application prints the text every time the user modifies the text, and it finishes the execution when the user writes the word ‘quit.’

The post Playing with coroutines and Qt appeared first on Qt Blog.





  


Разместил: Planet KDE | Дата: 29.05.2018 | Прочитано: 22 | Раздел: System & Utilities   

Рейтинг статьи

Средняя оценка: 0.00/0Средняя оценка: 0Всего голосов:0

Отлично
Хорошо Нормально Пойдёт Плохо


Смотрите также связанные темы

14.03.2008 new artist
author: ekko Summary: a lot of thing have been called art .do you know playing games can be called art just like http://www.vgoldsupply.com
19.04.2008 A Ruby Plasma Data Engine based on DBPedia SPARQL queries
Submitted by richard dale on Thu, 04/17/2008 - 19:08. KDE General I've been playing with using KIO::get() to make queries on the DBPedia SPARQL endpoint, parse the XML result set and convert it to be used by a ...
24.04.2008 audio/pidgin-musictracker - 0.4.1
MusicTracker is a plugin for Pidgin which displays the music track currently playing in the status message of various accounts such as AIM, Yahoo, MSN, Gtalk (Jabber), etc., i.e. any protocol Pidgin supports custom statuses on. Support for a wide range of audio players on both Windows and UNIX platforms is planned. Currently supported players: Amarok, Rhythmbox, Audacious, XMMS, MPC/MPD, Exaile, Banshee and Quod Libet. WWW: http://code.google.com/p/musictracker/
30.05.2009 KOffice Not Playing Well With MS Office
KOffice for the most part, has always been pretty solid software. Quicker than say, Open Office, it is designed to provide the casual KDE users just about everything they might want from a good office suite .
08.05.2011 Plasma + KWin = beautiful
Until last week I was still running good old Slackware 12.1 with KDE 3.5.something. I had skipped Slackware 13.0, because it had still no support for virtual screens in X/xrandr, and the KDE 4.4 in Slackware 13.1 crashed a few times while playing around with it.
24.05.2011 New Articles Published for Week Ending 5/21/11
New Articles Published for Week Ending 5/21/11 Apache Tomcat Determining your version of Tomcat (1033932) Date Published: 5/19/2011 VMware Converter VMware Converter fails with the error: Unable to create a VSS snapshot of the source volume(s) (1039087) Date Published: 5/20/2011 VMware ESX Cursor fails to interact with any objects in the bottom 3 inches of the screen of a full screen virtual machine. (1000467) Date Published: 5/20/2011 Exporting system logs fail for ESX/ESXi host fails with the error: A general system error occurred: internal error (1000558) Date Published: 5/20/2011 Wi...
21.12.2011 vExpert Spotlight: Kendrick Coleman
vExpert Spotlight: Kendrick Coleman Blog URL: http://www.kendrickcoleman.comTwitter handle: @KendrickColemanCurrent employer: VCE How did you get into IT? I've been into computers since I was a kid. I'm 28 so I'm a younger guy on the scene, but I remember playing Wheel of Fortune on 5 1/4" floppy disks on some ancient piece of hardware. Then I got my dads old Pentium with Windows 3.1 and I spent loads and loads of time getting myself into trouble in the old AOL days. I'll leave those days for another time. When I got to high school, I was still very much into technology...
19.02.2011 Top 5 Planet V12N blog posts for week 7
Top 5 Planet V12N blog posts for week 7 Happy Friday everyone, this week we have some great posts that cover the gamut.  Here are the top 5 picks for this week, enjoy the weekend! Chad Sakac - Updated 2011 vSphere ESXi 4.1 (and future) Homebrew/Whitebox parts list. - So, as I’ve said before, when things get political, and get all messy – I like going into the lab and spending a solid day just playing with tech.   It’s how I get back into a zen state.   That home lab powers a ton of VMs, and let’s me play, learn and stay fresh – not just on EMC stuff (using Virtual A...
11.11.2011 vExpert Spotlight: Julian Wood
vExpert Spotlight: Julian Wood Blog URL: http://www.WoodITWork.comTwitter Handle: @julian_wood  How did you get into IT? I started playing with computers at primary school in South Africa with yeh old BBC Micro and "programming" in logo and also typing in games from magazines. In high school, I was very lucky to be able to take Computer Studies as one of my subjects, which wasn't offered at most schools. Learned programming in Turbo Pascal, Clipper & dBase along with the basics of tape backups and CPUs. I was on the FidoNet BBS in the days before the Internet become ...
28.11.2011 vExpert Spotlight: Sohrab Kasraeian Fard
vExpert Spotlight: Sohrab Kasraeian Fard Twitter: @KasraeianBlog URL: http://www.kasraeian.com  How did you get into IT? It was about two years before school when for the first time I saw “Computers” in my father’s working place. When I was in the 1st year of my high school, I get the chance of playing games on the computer and one year after that I get some lessons about computer and MS DOS. I can say those event's changed my life completely as I leaved my first university after 2 years of studying “Material Engineering – Ceramic Field” and went to the new university for studying...
Нет комментариев. Почему бы Вам не оставить свой?
Вы не можете отправить комментарий анонимно, пожалуйста зарегистрируйтесь.
Google Search
Google

Web irc-unix.net

Топ Новостей
1: Linux distros aren\'t updating WebKit, making web browsers and email clients vulnerable
Hot NEWS!
Просмотров - 4962


2: Use ownCloud provided Packages, then VM, then Zip, no distro packages.
Просмотров - 642

3: Akonadi/KMail issues on Tumbleweed?
Просмотров - 611

4: New Year Calligra Words Sprint
Просмотров - 587

5: Netrunner Desktop 16.09 "Avalon" Linux OS Is Out with Kernel 4.7, KDE Plasma 5.7
Просмотров - 581

6: KDevelop 5.0.2 released for Windows and Linux
Просмотров - 552

7: HIG about Simple vs. Advanced Settings
Просмотров - 550

8: Interview with Esfenodon
Просмотров - 526

9: 3.0 Pre-alpha 3 is out!
Просмотров - 496

10: Multi-screen woes in Plasma 5.7
Просмотров - 484

11: Embrace Open Source culture: the 5 common transformations.
Просмотров - 474

12: Driving Akonadi Next from the command line
Просмотров - 472

13: GSoC Update 1: The Beginning
Просмотров - 466

14: [TORRENT] chakra-2016.02-ian-x86_64.iso
Просмотров - 464

15: Fedora and KDE/spin\'s treatment - Discussion
Просмотров - 462

Google 120X240
Ссылки

Главная | Actual Topics | Статьи | Обратная связь | Guest Book
Генерация: 0.858 сек. и 13 запросов к базе данных за 0.804 сек.
Powered by SLAED CMS © 2005-2007 SLAED. All rights reserved.