多线程
1. 线程概念的起源
- 单核CPU
早期还没有线程的概念,如何保证2个进程同时进行呢?时间片轮转调度
每次被CPU选中来执行当前进程所用的时间,时间一到,无论进程是否运行结束,操作系统都会强制将CPU这个资源转到另一个进程去执行。
- 多核CPU
随着运行的进程越来越多,人们发现进程的创建、撤销与切换存在着较大的时空开销,因此业界急需一种轻型的进程技术来减少开销。于是上世纪80年代出现了一种叫SMP的对称多处理技术,就是我们所知的线程概念。
线程切换的开销要小很多,这是因为每个进程都有属于自己的一个完整虚拟地址空间,而线程隶属于某一个进程,与进程内的其他线程一起共享这片地址空间,基本上就可以利用进程所拥有的资源而无需调用新的资源,故对它的调度所付出的开销就会小很多。
2. 三种方式创建线程
- 线程入口函数
#include <QThread>
void helloThread()
{
for (int i = 0; i < 99999999; ++i) {
qDebug() << "hello";
}
}
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QThread* th1 = QThread::create(helloThread);
th1->start();
return a.exec();
}
void helloThread(QString s)
{
for (int i = 0; i < 99999999; ++i) {
qDebug() << "hello" << s;
}
}
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QThread* th1 = QThread::create(helloThread, "thread1");
th1->start();
return a.exec();
}
class A {
public:
A() {
}
static void print()
{
for (int i = 0; i < 10; i++)
qDebug() << __FUNCTION__;
}
};
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
QThread* th1 = QThread::create(A::print);
th1->start();
return a.exec();
}
class A {
public:
A() {
}
void print()
{
for (int i = 0; i < 10; i++)
qDebug()