1. 程式人生 > >Qt與Boost多執行緒比較

Qt與Boost多執行緒比較

雖然mdl開發不支援多執行緒,如果不涉及mdl的API還是可以使用多執行緒的,比如QT的UI部分和SQL部分都可以啟用多執行緒。Qt的和Boost的thread都可以使用。

比較糾結的是二者之間的便捷性不同。習慣了隨意使用function啟動一個執行緒,就像用windows API那樣,Qt就不是那麼方便。Qt的多執行緒必須從Qthread繼承並實現run函式,呼叫start函式就可以啟動執行緒,有點繞。

#include <iostream>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/xtime.hpp>
using namespace boost;
using namespace std;

boost::mutex io_mu;

void print(int x,std::string str)
{
    // io互斥量,去掉此行io輸出會不正確
    mutex::scoped_lock lock (io_mu);
    std::cout << str << x << std::endl;
}

int main(int argc, char* argv[])
{
    thread t0 (&print, 10,"thread t0 : ");
    thread t1 (&print, 11,"thread t1 : ");
    thread t2 (&print, 12,"thread t2 : ");

    t0.join ( );
    t1.join ( );
    t2.join ( );

    return 0;
}

用Boost實現QThread的形式,採用類內部的函式呼叫,與QThread呼叫方式極相似:

class qprinter : public QThread
{
    QString m_str;
public:
    qprinter(QString str):m_str(str){}
    virtual void run ( )
    {
        for (int i = 0; i != 5; ++i)
        {
            boost::mutex::scoped_lock lock (io_mu);
            std::cout << m_str.toLatin1 ( ).data ( ) << i << std::endl;
        }
    }

};

class BoostbaseThread
{
public:
    virtual void run ( ) = 0;
    void start ( )
    {
        boost::thread t (&BoostbaseThread::run, this);
        t.join ( );
    }
};

class bprinter : public BoostbaseThread
{
    std::string m_str;
public:
    bprinter (std::string str) :m_str (str) {}

    virtual void run ( )
    {
        for (int i = 0; i != 5; ++i)
        {
            boost::mutex::scoped_lock lock (io_mu);
            std::cout << m_str << i << std::endl;
        }
    }

};

int main (int argc, char* argv [])
{
    QApplication app (argc, argv);
    
    qprinter printA ("A : ");
    qprinter printB ("B : ");
    printA.start ( );
    printB.start ( );

    bprinter printC ("C : ");
    bprinter printD ("D : ");
    printC.start ( );
    printD.start ( );

    return app.exec();
}

QThread是參照Java的多執行緒進行設計的,對於支援全域性函式的C++完全沒必要這麼玩。用類來封裝還是太囉嗦了吧。