进程是资源分配的最小单位。进程有单独地址空间,一个进程崩溃可以不影响其它进程。
线程是运行调度的最小单位。线程共享地址空间,一个线程崩溃整个进程会结束。线程基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈)。
1. 使用普通函数创建线程
join后的代码要等线程结束后才运行。detach后子线程与主线程脱离关系,主线程结束子线程继续运行,但程序结束时子线程也会结束。
void fun1() {
cout << "--thread id: "<< std::this_thread::get_id() << endl;
}
void fun2(int a, int* p, int& r) {
(*p)++;
r++;
}
int main() {
int pa = 1, pb = 2, pc = 3;
thread th1 = thread(fun1);
thread th2 = thread(fun2, pa, &pb, ref(pc));
th1.join();
th2.join();
return 0;
}
这个例子展示的是使用普通函数创建线程,不传参数和传多个不同类型参数的方法。注意,传引用时,实参要放在 std::ref() 中。
2. 使用成员函数创建线程
使用非静态成员函数创建线程。
struct Example {
Example(int x) { a = x; }
void fun1() { cout << "Ite=" << a << endl; }
void fun2(int& sum, mutex& mx) {
for (int i = 0; i < a; i++) {
mx.lock();
sum++;
mx.unlock();
}
}
int a;
};
int main() {
int sum = 0;
mutex mx;
Example ex(100000);
thread th1 = thread(&Example::fun1, ex);
thread th2 = thread(&Example::fun2, ex, ref(sum), ref(mx));
thread th3 = thread(&Example::fun2, ex, ref(sum), ref(mx));
th1.join();
th2.join();
th3.join();
cout << "sum=" << sum << endl;
}
这个例子展示了使用成员函数创建线程,不传参数和传多个参数的方法。其中,实参是整数和互斥锁。