QT執行緒(一):執行緒類
執行緒之間共享資料,但又單獨執行;
QT執行緒QThread是平臺無關的;
通常主執行緒從main開始執行,而在主執行緒中建立其他執行緒,其他執行緒派生於QThread;
1、執行緒優先順序
總共8個優先順序:執行緒優先順序從上到下越來越高。
Constant |
Value |
Description |
QThread::IdlePriority |
0 |
scheduled only when no other threads are running. |
QThread::LowestPriority |
1 |
scheduled less often than LowPriority. |
QThread::LowPriority |
2 |
scheduled less often than NormalPriority. |
QThread::NormalPriority |
3 |
the default priority of the operating system. |
QThread::HighPriority |
4 |
scheduled more often than NormalPriority. |
QThread::HighestPriority |
5 |
scheduled more often than HighPriority. |
QThread::TimeCriticalPriority |
6 |
scheduled as often as possible. |
QThread::InheritPriority |
7 |
use the same priority as the creating thread. This is the default. |
2、執行緒管理
2.1、執行緒啟動
void |
start ( Priority priority = InheritPriority ) 啟動執行緒執行,啟動後會發出started訊號。 |
2.2、執行緒執行
int |
exec () 進入執行緒eventloop。 |
virtual void |
run () 執行緒入口。 |
2.3、執行緒退出
void |
quit () 相當於exit(0)。 |
void |
exit ( int returnCode = 0 ) 呼叫exit後,thread將退出event loop,並從exec返回,exec的返回值就是returnCode。 通常returnCode=0表示成功,其他值表示失敗。 |
void |
結束執行緒,執行緒是否立即終止取決於作業系統。 執行緒被終止時,所有等待該執行緒Finished的執行緒都將被喚醒。 terminate是否呼叫取決於 ( bool enabled = true )開關。 |
2.4、執行緒等待
void |
( unsigned long msecs ) |
void |
sleep ( unsigned long secs ) |
void |
( unsigned long usecs ) |
bool |
wait ( unsigned long time = ULONG_MAX ) 執行緒將會被阻塞,等待time毫秒。和sleep不同的是,如果執行緒退出,則wait會返回。 |
2.4、執行緒狀態
bool |
執行緒是否已退出。 |
bool |
執行緒是否還處於執行態。 |
2.5、執行緒屬性
Priority |
|
void |
( Priority priority ) |
void |
|
void |
設定是否響應terminate()。 |
3、執行緒例項
當我們建立執行緒時,首先是從QThread派生類定義一個新的執行緒,然後再使用該執行緒時,建立該執行緒類的物件。
例如:
class MyThread : public QThread
{
protected:
void run(); /* 過載run */
};
{
QTcpSocket socket;
socket.connectToHost(hostName, portNumber); /* 建立tcp連線 */
exec(); /* 進入事件迴圈 */
}
int main()
{
MyThread thread; /* 使用新建立的thread */
thread.start(); /* thread會執行run(),建立tcp連線並進入事件迴圈,直到thread終止退出事件迴圈 */
thread.wait(); /* 等待thread退出 */
return 0;
}
從QThread派生類時,需要重新實現QThread的虛擬函式run。
void QThread::run ()[virtual protected]
該函式是執行緒的入口,當我們使用start()啟動執行緒時,新執行緒就會執行run()。預設的run()函式就僅僅呼叫了exec()進入事件迴圈。
當然,定義自己的執行緒run()時,也可以不使用事件迴圈,
例如:
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
void setMessage(const QString &message);
void stop();
protected:
void run();
private:
QString messageStr;
volatile bool stopped;
};
Thread::Thread()
{
stopped = false;
}
void Thread::run()
{
while (!stopped) /* 該thread就沒有用到exec()進入事件迴圈 */
std::cerr << qPrintable(messageStr);
stopped = false;
std::cerr << std::endl;
}
void Thread::stop()
{
stopped = true;
}
FROM: http://blog.csdn.net/calm_agan/article/details/6300709