[toc]

# 进程与线程的简单区别

  • 地址空间和其他资源: 进程间相互独立,同一进程的各线程间共享。某进程内的线程在其它进程不可见。
  • 通信:进程间通信 IPC,线程间可以直接读写进程数据段(如全局变量)来进行通信–需要进程同步和互斥手段的辅助,以保证数据的一致性。
  • 调度和切换:线程上下文切换比进程上下文切换要快得多。
  • 多线程 OS 中,进程不是一个可执行的实体。

# 踩坑记录

官网下载的 release 版本的 MinGW 不带 threads-poixs 支持,所以得下载这个版本并且覆盖到 mingw 根目录下 http://sourceforge.net/projects/mingwbuilds/files/host-windows/releases/4.8.1/64-bit/threads-posix/sjlj/

# 五种创建线程的方式

  • 函数指针
  • Lambda 函数
  • Functor (仿函数)
  • 非静态成员函数
  • 静态成员函数

# 函数指针

//
// Created by light on 20-1-31.
//
#include
#include
#include

using namespace std::chrono;
using namespace std;

/**
* 1. 普通函数指针
* 2.Lambda 函数
* 3.Functors
* 4. 非静态成员函数
* 5. 静态成员函数
*/

using ull = unsigned long long;
ull OddSum = 0;
ull EvenSum = 0;

void findEven(ull start, ull end) {
for (ull i = start; i <= end; ++i)
if ((i & 1) == 0)
EvenSum += i;
}

void findOdd(ull start, ull end) {
for (ull i = start; i <= end; ++i)
if ((i & 1) == 1)
OddSum += i;
}

int main() {

ull start = 0, end = 1900000000;


auto startTime = high\_resolution\_clock::now();

std::thread t1(findEven,start,end);
std::thread t2(findOdd,start,end);

t1.join();
t2.join();

auto stopTime = high\_resolution\_clock::now();
auto duration = duration\_cast<microseconds>(stopTime - startTime);
cout << "OddSum : " << OddSum << endl;
cout << "EvenSum: " << EvenSum << endl;
cout << "Sec: " << duration.count() / 1000000 << endl;


cin.get();

return 0;

}

thread 是开始线程,但是如果在线程开启以后想要等待线程结束,就需要调用 join