1. Create and use threads
void showInfo()
{
std::thread::id id = std::this_thread::get_id();//当前线程id
debug "执行showInfo()" << std::hash<std::thread::id>()(id);
}
-
Specify a function when creating a thread object, and run this function in other threads:
std::thread t1{showInfo};
int main(int argc, char *argv[])
{
std::thread t1{showInfo};
std::thread t2{showInfo};
t1.join();//等待线程运行
t2.join();
std::thread::id id1 = t1.get_id();
std::thread::id id2 = t2.get_id();
std::thread::id id = std::this_thread::get_id();//当前线程id
debug std::hash<std::thread::id>()(id1);
debug std::hash<std::thread::id>()(id2);
debug std::hash<std::thread::id>()(id);
}
-
Specify the function object when creating a thread
struct ceshi
{
void operator () ()
{
debug "run ceshi";
}
};
int main(int argc, char *argv[])
{
std::thread t1{ceshi()};
t1.join();//等待线程运行
std::thread::id id1 = t1.get_id();
debug std::hash<std::thread::id>()(id1);
}
2. Passing parameters
void showInfo(const QString & string)
{
debug "执行showInfo() start";
debug "当前线程id = " <<std::hash<std::thread::id>()(std::this_thread::get_id());
debug string;
debug "执行showInfo() end";
}
int main(int argc, char *argv[])
{
std::thread t1{showInfo,"我是一个字符串11111"};
t1.join();
debug endl;
std::thread t2{showInfo,"我是一个字符串22222"};
t2.join();
}
When passing a non-const reference, add std::ref(), otherwise the compilation may fail:
void showInfo(QString & string)
{
debug string;
}
int main(int argc, char *argv[])
{
QString src = "我是一个字符串";
std::thread t1{showInfo,std::ref(src)};
t1.join();
}