C++多线程
-
#include <thread>
:C++多线程库 -
#include <mutex>
:C++互斥量库 -
#include <future>
:C++异步库
多线程介绍
线程的创建
void entry_1() { }以普通函数作为线程入口函数:
void entry_2(int val) { }
std::thread my_thread_1(entry_1);
std::thread my_thread_2(entry_2, 5);
以类对象作为线程入口函数:
class Entry
{
void operator()() { }
void entry_function() { }
};
Entry entry;
// 调用operator()()
std::thread my_thread_1(entry);
// 调用Entry::entry_function
std::thread my_thread_2(&Entry::entry_function, &entry);
以lambda表达式作为线程入口函数:
// 运行结果
std::thread my_thread([]() -> void
{
// ...
});
// 举例
#include <iostream>
#include <thread>
#include <mutex>
#include <future>
#include <string>
#include <limits>
using namespace std;
int main() {
// 获取 size_t 类型的最小值
constexpr size_t min_size_t = std::numeric_limits<size_t>::min();
std::cout << "min_size_t = " << min_size_t << std::endl;
// 获取 size_t 类型的最大值
constexpr size_t max_size_t = std::numeric_limits<size_t>::max();
std::cout << "max_size_t = " << max_size_t << std::endl;
// 开启子线程1
std::thread thread1([]()->void {
for (size_t i = 0; i < 2; i++)
{
for (size_t i = 0; i < 2; i++)
{
std::cout << "hardware_concurrency1 = " << std::thread::hardware_concurrency() << std::endl;
}
}
});
// 开启子线程2
std::thread thread2([]()->void {
std::cout << std::endl;
for (size_t i = 0; i < 2; i++)
{
for (size_t i = 0; i < 2; i++)
{