创建线程

  进程是资源分配的最小单位。进程有单独地址空间,一个进程崩溃可以不影响其它进程。
  线程是运行调度的最小单位。线程共享地址空间,一个线程崩溃整个进程会结束。线程基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈)。

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;
}

  这个例子展示了使用成员函数创建线程,不传参数和传多个参数的方法。其中,实参是整数和互斥锁。

3. std::mem_fn 和 std::async

4. 设计线程池

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值