Qt_Core_AD_3 - 8BitsCoding/RobotMentor GitHub Wiki


๋‹จ, ์•„๋ž˜์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ QThread๋ฅผ ์ƒ์†ํ•˜์—ฌ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ์ถ”์ฒ˜ํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค.

// main.cpp
#include <QtCore/QCoreApplication>

#include <qtimer.h>
#include <qsharedpointer.h>

#include "test.h"

static QSharedPointer<test> sptr;

void timeout()
{
	if (!sptr.isNull()) {
		qInfo() << "Timerout Stopping Thread";
		sptr.data()->quit();
	}
}

int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);

	test thread;
	sptr.reset(&thread);
	thread.start();

	QTimer timer;
	timer.singleShot(5000, &timeout);

	return a.exec();
}
// test.h
#pragma once

#include <QObject>
#include <qdebug.h>
#include <qthread.h>

class test : public QThread
{
	Q_OBJECT

public:
	explicit test(QObject *parent = nullptr);
	~test();

signals:

public slots:
	void quit();

protected:
	void run();

private:
	bool ok;

};
// test.cpp
#include "test.h"

test::test(QObject *parent)
	: QThread(parent)
{
}

test::~test()
{
}

void test::quit()
{
	ok = false;
	QThread::quit();
}


void test::run()
{
	ok = true;
	for (int i = 0; i < 1000; i++)
	{
		qInfo() << i;
		this->sleep(1);
		// this is bad because now code become unpredictable
		// control can come from anywhere

		if (!ok) break;
	}

	qInfo() << "Finished";
}

์ด๋ฏธ์ง€

โš ๏ธ **GitHub.com Fallback** โš ๏ธ