首页 > 技术知识 > 正文

Qt中实现C++线程操作一(使用线程)

一般来说每个操作系统或者是开发IDE都会提供线程API。但是本篇文章介绍的不是操作系统或者IDE提供的线程API,而是C++的线程库,自C++11开始后C++有了标准的线程库:std::thread,各种支持C++11及更改版本的IDE都可以使用,便于是使用C++开发多线程库供多平台使用。 话不多说,直接上代码简单明了: 例程1:

#include <thread> #include <iostream> //线程函数 void f1(){ for(int i = 0;i<20;i++) { std::cout << “f1\n”; std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } void f2(){ for(int i = 0;i<20;i++) { std::cout << “f2\n”; } } int main(int argc, char *argv[]) { //实例化一个线程对象t1,使用函数f1构造,然后该线程就开始执行了(f1()) std::thread t1(f1); //实例化一个线程对象t2,使用函数f2构造,然后该线程就开始执行了(f2()) std::thread t2(f2); return 0; }
<

运行后发现线程函数正常运行,但是程序会报错,如下所示: Qt中实现C++线程操作一(使用线程) 这是因为创建了线程后线程开始执行,但是主线程main()并没有停止脚步,仍然继续执行然后退出,此时创建的子线程还在运行,线程仍然存在但指向它的线程对象已经销毁,所以会抛出异常。 那么怎样才能保证主线程在子线程退出后再退出呢?

thread::join() 使用thread::join()接口可解决上述问题 #include <thread> #include <iostream> void f1(){ for(int i = 0;i<20;i++) { std::cout << “f1\n”; } } void f2(){ for(int i = 0;i<20;i++) { std::cout << “f2\n”; } } int main(int argc, char *argv[]) { std::thread t1(f1); std::thread t2(f2); t1.join(); t2.join(); std::cout << “this is Main \n”; return 0; }
<

运行结果: Qt中实现C++线程操作一(使用线程)1 本次运行正常没有再出现异常,可从运行结果可以看到“this is Main”这句话是在子线程运行完成后才打印的,这说明thread::join()接口会堵塞主线程。 thread::detach() thread::detach()接口也可以解决最开始的异常问题,detach是用来和线程对象分离的,这样线程可以独立地执行,不过这样由于没有thread对象指向该线程而失去了对它的控制,当对象析构时线程会继续在后台执行,但是当主程序退出时并不能保证线程能执行完。如果没有良好的控制机制或者这种后台线程比较重要,最好不用detach而应该使用join。

int main(int argc, char *argv[]) { std::thread t1(f1); std::thread t2(f2); t1.detach(); t2.detach(); std::cout << “this is Main \n”; return 0; }

由结果可见线程并没有执行完而退出:Qt中实现C++线程操作一(使用线程)2

猜你喜欢