C++多线程编程

多线程用法


1.多线程创建

  • (1) 创建一个thread,并传入一个方法;
#include <thread>
#include <iostream>

using namespace std;

void HelloWorld() {
    cout << "Hello, World!" << endl;
}

int main() {
    thread th(HelloWorld);
	th.join();
    return 0;
}


2.多线程传参

  • (1) 创建一个thread,传入一个函数指针,及需要传入函数的参数;
  • (2) 创建一个thread,传入一个函数对象,及需要传入函数对象的参数;
  • (3) 创建一个thread,传入一个lambda表达式,及需要传入lambda表达式的参数;
#include <thread>
#include <iostream>

using namespace std;

// 1.传入一个函数指针
void Func(int x) {
	for (int i = 0; i < x; ++i) {
		cout << "线程使用函数指针传参." << endl;
	}
}

// 2.传入一个函数对象
class FuncObj {
public:
	void operator()(int x) {
		for (int i = 0; i < x; ++i) {
			cout << "线程使用函数对象传参." << endl;
		}
	}
};

int main() {
	thread th1(Func, 3);
	thread th2(FuncObj(), 3);
    // 3.传入一个lambda函数
	auto lambdaF = [](int x) {
		for (int i = 0; i < x; ++i) {
			cout << "线程使用Lambda函数传参." << endl;
		}
	};
	thread th3(lambdaF, 3);
	th1.join();
	th2.join();
	th3.join();

	return 0;
}

这里需要注意,传入的参数是引用形式,需要使用std::ref,并且可以通过this_thread::get_id()方法获取当前线程id,如:

#include <iostream>
#include <thread>

using namespace std;

void func(int& result) {
	std::cout << "Func thread ID: " << this_thread::get_id() << endl;
	int res = 0;
	for (int i = 0; i < 100; ++i) {
		res += i;
	}
	result = res;
}

int main() {
	int result = 0;
	thread th(func, std::ref(result));
	th.join();

	std::cout << "Main thread ID: " << this_thread::get_id() << endl;
	cout << result << endl;

	return 0;
}


3.多线程lambda函数捕获

  • (1) lambda表达式分为两个部分,第一个部分为catch捕获的外部变量对应[],第二个部分为传入的参数列表对应(),如:
#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "test";
	auto f = [&str](int a, int b) {
		cout << str << endl;
		cout << a + b << endl;
	};
	f(1, 2);

	return 0;
}

  • (2) 将lambda表达式作为thread传参:
#include <iostream>
#include <string>
#include <thread>

using namespace std;

int main() {
	string str = "test";
	thread func = thread([&str](int a, int b) {
		cout << str << endl;
		cout << a + b << endl;
	}, 1, 2);

	func.join();

	return 0;
}

  • 这里局部变量str传入线程,需要用捕获的方式,否则需要将其定义为全局变量才可以:
#include <iostream>
#include <string>
#include <thread>

using namespace std;
string str = "test";
int main() {
	thread func = thread([](int a, int b) {
		cout << str << endl;
		cout << a + b << endl;
	}, 1, 2);

	func.join();

	return 0;
}


4.多线程加速

  • (1) 任务切割:将一个任务切割成多个子任务;
  • (2) 多线程加速:每个子任务开一个线程执行,从而实现加速的目的;
#include <iostream>
#include <thread>
#include <chrono>

using namespace std;
using namespace std::chrono;

template <class T>
void Measure(T&& func) {
	auto start = system_clock::now();
	func();
	duration<double> diff = system_clock::now() - start;
	cout << "TimeCost: " << diff.count() << " seconds." << endl;
}

void Sum(long start, long end, long& ans) {
	long s = 0;
	for (long i = start; i < end; ++i) {
		s += i;
	}
	ans = s;
}

const long S = 100000000;

int main() {
	Measure([]() {
		long ans1, ans2;
		thread t1 = thread(Sum, 0, S / 2, ref(ans1));
		thread t2 = thread(Sum, S / 2, S, ref(ans2));
		t1.join();
		t2.join();
		cout << "Ref Answer: " << (ans1 + ans2) << endl;
	});

	Measure([]() {
		long ans;
		Sum(0, S, ans);
		cout << "Normal Answer: " << ans << endl;
	});

	return 0;
}

  • 注意,当任务计算量比较小时,线程创建和销毁比例就比较多,这个时候多线程达不到加速的目的,可以将程序中的S减小看看。

5.异步执行

  • (1) async和future:async是异步执行的意思,返回值类型为future;
  • (2) 获取值的时候,使用get()方法,等待当前线程执行完毕;
#include <iostream>
#include <thread>
#include <chrono>
#include <future>

using namespace std;
using namespace std::chrono;

template <class T>
void Measure(T&& func) {
	auto start = system_clock::now();
	func();
	duration<double> diff = system_clock::now() - start;
	cout << "TimeCost: " << diff.count() << " seconds." << endl;
}

long Sum(long start, long end) {
	long s = 0;
	for (long i = start; i < end; ++i) {
		s += i;
	}
	return s;
}

const long S = 100000000;

int main() {
	Measure([]() {
		const long K = 2;
		const long Step = S / K;
		vector<future<long>> vf;
		vf.reserve(K);
		for (int i = 0; i < K; ++i) {
			vf.push_back(async(
				Sum, i == 0 ? 0 : Step * i,
				i == K - 1 ? S : Step * (i + 1))
			);
		}
		long ans = 0;
		for (int i = 0; i < K; ++i) {
			ans += vf[i].get();
		}
		cout << "Async: " << ans << endl;
	});

	Measure([]() {
		long ans = Sum(0, S);
		cout << "Normal Answer: " << ans << endl;
	});

	return 0;
}


6.锁问题

  • (1) 多个线程对对同一个变量操作,会出现数据竞态问题;
  • (2) 加锁的目的是为了保证同一个时刻,只有一个线程能够对变量进行操作;
#include <thread>
#include <mutex>
#include <iostream>
#include <chrono>
#include <vector>

using namespace std;
using namespace std::chrono;

mutex mtx;

template <class T>
void Measure(T&& func) {
	auto start = system_clock::now();
	func();
	duration<double> diff = system_clock::now() - start;
	cout << "TimeCost: " << diff.count() << " seconds." << endl;
}

void Sum(int& s) {
	mtx.lock();
	for (int i = 0; i < 1000000; ++i) {
		s++;
	}
	mtx.unlock();
}

int main() {
	Measure([]() {
		vector<thread> vf;
		int s = 0;
		for (int i = 0; i < 4; ++i) {
			vf.emplace_back(Sum, std::ref(s));
		}
		for (int i = 0; i < 4; ++i) {
			vf[i].join();
		}
		cout << s << endl;
	});

	return 0;
}

参考资料

C++多线程快速入门

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值