std::thread 是C++11 引入的一个类,用于表示一个独立的执行线程。它允许程序同时执行多个任务。使用 std::thread,你可以很容易地创建新的线程来运行指定的函数或可调用对象。 2. 阐述std::thread的返回值类型 std::thread 的构造函数执行后,会立即返回一个 std::thread 类型的对象。但是,std::thread 本身的构...
#include<iostream>#include<thread>voidprint_thread_id(){std::thread::id thread_id=std::this_thread::get_id();std::cout<<"Thread ID: "<<thread_id<<std::endl;}intmain(){std::threadt1(print_thread_id);std::threadt2(print_thread_id);t1.join();t2.join();return0;} ...
#include <thread> #include <future> int func() { return 1; } std::future<int> ret = std::async(&func); int i = ret.get(); 我无法评论它是否适用于 所有 平台(它似乎适用于 Linux,但不适用于我在带有 GCC 4.6.1 的 Mac OSX 上构建)。 原文由 Alex B 发布,翻译遵循 CC BY-SA 3.0 ...
//async的使用,配合future直接获取多线程中所调用函数的返回值#include<iostream>#include<thread>#include<future>intf(inta,intb){ using namespacestd::chrono_literals;std::this_thread::sleep_for(5s);//睡眠五秒returna + b; }intmain(){std::future<int> retVal =std::async(f,2,4);std::cout<...
voidthreadFunction(){std::cout<<"Running in another thread"<<std::endl;}intmain(){std::threadmyThread(threadFunction);myThread.join();// 等待线程结束return0;} Lambda表达式 更灵活的方式是使用lambda表达式,可以捕获外部变量: 代码语言:cpp ...
std::thread是 C++ 11 新引入的标准线程库。在同样是 C++ 11 新引入的 lambda 函数的辅助下,std::thread用起来特别方便: int a = 1; std::thread thread([a](int b) { return a + b; }, 2); 它唯一有点令人疑惑的地方在于其提供的join和detach函数,字面上的意思是前者合并线程,后者分离线程。无...
join(); cout << "main end: x = " << x << endl; return 0; } 执行结果: thread_func: a = 20 main end: x = 20 1.1.2、主要成员函数 (1)get_id():获取线程ID,返回类型std::thread::id对象。(2)joinable():判断线程是否可以加入等待。(3)join():等该线程执行完成后才返回。(4)...
初始化构造函数,创建一个 std::thread 对象,该 std::thread 对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。 拷贝构造函数(被禁用),意味着 std::thread 对象不可拷贝构造。 Move 构造函数,move 构造函数(move 语义是 C++11 新出现的概念,详见附录),调用成功之后 x 不代表任何 ...
使用std::thread只需要一个cpp编译器,可以快速、方便地创建线程,但在async面前,就是小巫见大巫了(注:std::async定义在future头文件中,async是一个函数,所以没有成员函数)。 boost::thread是一个可移植的库,可在各种平台/编译器上进行编译-包括std :: thread不可用的平台。
} void test() { unordered_map<int, int> ht; thread t[2]; t[0] = thread(thread_add, ht, 0, 9); t[1] = thread(thread_add, ht, 10, 19); t[0].join(); t[1].join(); std::cout << "size: " << ht.size() << std::endl; } int main() { test(); return 0; }...