雖然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++完全沒必要這麼玩。用類來封裝還是太囉嗦了吧。