Skip to content

Instantly share code, notes, and snippets.

@minlexx
Last active February 14, 2020 16:11
Show Gist options
  • Save minlexx/edffd0f4434e6d0d5058fdc1d4b30baf to your computer and use it in GitHub Desktop.
Save minlexx/edffd0f4434e6d0d5058fdc1d4b30baf to your computer and use it in GitHub Desktop.
test_threaded_socketnotifier
Thread: started!
Thread: writing: Write 0
ready to read!
read: Write 0
Thread: writing: Write 1
ready to read!
read: Write 1
Thread: writing: Write 2
ready to read!
read: Write 2
Thread: writing: Write 3
ready to read!
read: Write 3
Thread: writing: Write 4
Thread: exiting
ready to read!
read: Write 4
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QObject>
#include <QThread>
#include <QDebug>
#include <stdlib.h> // EXIT_FAILURE
#include <unistd.h> // read, write, close, pipe
#include <limits.h> // PIPE_BUF
#define READ_END 0
#define WRITE_END 1
/**
* @brief The ThreadedWriter class
* Yes, I know: deriving from QThread is bad practice.
* But good enough for this short example.
*/
class ThreadedWriter: public QThread
{
private:
int write_fd = 0;
public:
explicit ThreadedWriter(int wfd, QObject *parent = nullptr)
: QThread(parent)
, write_fd(wfd)
{
}
virtual void run() override {
int i;
char buf[32];
qDebug() << "Thread: started!";
for (i = 0; i < 5; i++) {
QThread::msleep(1000);
snprintf(buf, sizeof(buf) - 1, "Write %d", i);
qDebug() << "Thread: writing:" << buf;
::write(write_fd, buf, sizeof(buf));
}
qDebug() << "Thread: exiting";
quit();
}
};
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
int fd[2] = {0, 0};
if (::pipe(fd) == -1) {
return EXIT_FAILURE;
}
ThreadedWriter tw(fd[WRITE_END]);
QObject::connect(&tw, &QThread::finished, &app, &QCoreApplication::quit);
QSocketNotifier sn(fd[READ_END], QSocketNotifier::Read);
QMetaObject::Connection conn = QObject::connect(&sn, &QSocketNotifier::activated, &sn, [](int sock) {
Q_UNUSED(sock)
qDebug() << " ready to read!";
char buf[PIPE_BUF] = {0};
::read(sock, buf, sizeof(buf) - 1);
qDebug() << " read:" << buf;
});
tw.start();
// { MAIN EVENT LOOP
const int mainret = app.exec();
// } MAIN EVENT LOOP
QObject::disconnect(conn);
::close(fd[READ_END]);
::close(fd[WRITE_END]);
return mainret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment