Qt多线程的实现方式

参考:

[1].Qt的4种多线程实现方式

[2].C++ std::thead class


简介QThread类

一、公共槽函数:

1)start():开始线程的执行,内部调用run()函数,run()又调用exec()。

2)quit():告诉线程的事件循环停止运行,并返回0(成功),等价于调用exit(0);

3)terminiate():「不推荐使用该函数」终止线程的执行。线程可能不会立即终止,取决于操作系统的调度。

二、信号:

1)started():在start()之后,在run()之前发射。

2)funished():在线程将要停止执行时发射。发射时,线程已经停止事件循环。不再执行新的事件,但是deferred deletion事件除外。可以把该信号连接到本线程中的对象的deleteLater()槽中。

三、公共函数:

wait():等待线程停止执行,通常和quit()配合使用。

方法1:把对象moveToThread到QThread中

适用场景:需要信号和槽通信

原理:对象使用线程的事件循环,然后外部给对象发送消息,对象就会在线程里执行槽函数。

注意:通常把线程的finished()信号连接到线程内对象的deleteLater()槽上,用来释放该对象。

QThread官方给的范例

方法2:用C++的std::thead类

适用场景:不需要信号和槽通信。

参考:https://www.cplusplus.com/reference/thread/thread/


std::this_thread的4个静态函数


thread的4个构造函数,第1个只构建对象,没有线程执行;第2个即构建对象也执行线程


thread默认构造函数生成的对象不是joinable

std::thread::detach:调用该函数后,calling thread(例如主线程)和detached thread(例如次线程)各自独立运行,且彼此无法同步或阻塞;任意一个线程执行完毕,它的资源被释放。调用该detach函数后,thread对象编程not-jionable状态,就可以被安全销毁了。被detached的线程相当于是断了线的风筝,独立运行,不再受thread对象控制。即使thread对象被销毁,线程仍可以继续运行。

线程中等号“=”转移线程所有权

std::thread::join:等待线程执行完毕。


3种不能被join的情况

注意:运行类的成员函数时,需要传递隐形的this指针参数

// thread example

#include       // std::cout

#include         // std::thread

class A{

public:

    void test(){ std::cout<<"A::test() is calling\n";}

};

void foo()

{std::cout<<"foo is running in thread id:"<

int main()

{

    A a;

  std::thread first (foo);    // spawn new thread that calls foo()

  std::thread second(&A::test, &a); //new thread that call member function of Class A

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:

  first.join();                // pauses until first finishes

  second.join();              // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;

}

你可能感兴趣的:(Qt多线程的实现方式)