标准库(C++0x)中的 thread 用起来似乎蛮简单的。
例子
一个 std::thread 对象可以接收
- 普通的函数
- 函数对象
- 类的成员函数
- lambda 函数
作为参数。
- 普通的函数
- 函数对象
- 类的成员函数
- 以及lambda函数
- 主程序
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::thread t1(test1);
std::thread t2(test2, "test 2");
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");
std::thread t7([](const QString & text){qDebug()<<"hello"<<text;}, "test7");
return a.exec();
}
备忘
- 添加了两层括号(不然会被编译器认作一个名为t3的函数的声明)
std::thread t3((Test3()));
- std::bind ? 带参数,比如:
std::thread t2(test2, "test 2");
要写成
std::thread t2(std::bind(test2, "test 2"));
那一个标准?
- std::ref ? (函数对象,或者参数,都是传值,传引用需要使用std::ref),比如对前面的Test3
Test3 test3;
test3();
std::thread t3(test3);
std::thread t33(std::ref(test3));
这三次调用的结果(类似于):
hello test3 0xbfc3b27f hello test3 0xbfc3b27f hello test3 0x9811e60
本文展示了如何在C++0x标准库中使用thread,包括使用普通函数、函数对象、类的成员函数及lambda函数作为参数创建线程。
469

被折叠的 条评论
为什么被折叠?



