关于线程,之前用的最多的就是C语言的 pthread 系列函数; QT中也有QThread 类可以直接用。 偶然发现C++11 中早已经拥有了一个更好用的线程类std::thread 下面简单介绍一下std::thread的基本用法吧
#include <thread>
bool HelloWorld::init()
{
std::thread t1(&HelloWorld::firstThread,this);//创建一个分支线程,回调到firstThread函数里
t1.join(); //等待子线程firstThread执行完之后,主线程才可以继续执行下去,此时主线程会释放掉执行完后的子线程资源
//线程可传参
std::thread t2(&HelloWorld::secondThread,this,10,20);//创建一个分支线程,回调到secondThread函数里
t2.detach(); //将子线程从主线程里分离,子线程执行完成后会自己释放掉资源; 分离后的线程,主线程将对它没有控制权
LOG("in major thread");//在主线程
return true;
}
void HelloWorld::firstThread()
{
LOG("in first thread");//在子线程
}
void HelloWorld::secondThread(int first,int second)
{
LOG("in second thread,first = %d,second = %d",first,second);
}
初始化互斥锁
std::mutex mutex;//线程互斥对象
mutex.lock(); //加锁
mutex.unlock(); //解锁
这里就不写例子解释锁的用法了。
各种std::thread调用的用法例子:
void test1()
{
qDebug()<<"hello test 1";
}
void test2(const QString &text)
{
qDebug()<<"hello"<<text;
}
class Test3
{
public:
Test3(){}
void operator()() const
{
qDebug()<<"hello test3"<<this;
}
};
class Test4
{
public:
QString a;
Test4(const QString a):a(a){}
void operator()(const QString b) const
{
qDebug()<<a<<b;
}
};
class Test5
{
public:
void output()
{
qDebug("hello test 5");
}
};
class Test6
{
public:
void output(const QString & text)
{
qDebug()<<"hello"<<text;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//普通的函数
std::thread t1(test1);
//std::thread t2(std::bind(test2, "test 2"));
std::thread t2(test2, "test 2");
//添加了两层括号(不然会被编译器认作一个名为t3的函数的声明)
std::thread t3((Test3()));
//函数对象
std::thread t4(Test4("hello"), "test 4");
//类的成员函数
Test5 test5;
std::thread t5(&Test5::output, &test5);
Test6 test6;
std::thread t6(&Test6::output, &test6, "test 6");
//lambda函数
std::thread t7([](const QString & text){qDebug()<<"hello"<<text;}, "test7");
return a.exec();
}