c++ 线程使用详解 lamba std::function 传递引用 类成员函数

编程入门 行业动态 更新时间:2024-10-23 02:39:44

c++ <a href=https://www.elefans.com/category/jswz/34/1771240.html style=线程使用详解 lamba std::function 传递引用 类成员函数"/>

c++ 线程使用详解 lamba std::function 传递引用 类成员函数

c++ 线程

std::thread

  • 头文件 #include <thread>
  • 用于创建并控制线程。
  • 顶层函数:线程需要运行的函数。
  • 顶层函数作为构造函数参数传递给该对象。
  • 对象构造时,线程以顶层函数作为入口函数并开始运行(等待任何OS调度延迟)。
  • 顶层函数的返回值将被忽略,但仍有其他方法可以获取其返回值,比如修改共享变量或使用 std::promise 等。
  • 顶层函数若以抛出异常中止,则调用 std::terminate
  • 对于 joinable 的线程对象,不再需要该线程时,调用者必须调用其 join 方法终止线程,否则该线程对象析构时会调用 std::terminate
  • 没有任何两个 std::thread 对象会表示同一执行线程。
  • std::thread 对象也可能处于不表示任何线程的状态(默认构造、被移动、 detach 或 join 后),并且执行线程可能与任何 thread 对象无关( detach 后)。

std::thread 最常用构造函数

  • 函数原型:

    template< class Function, class... Args >
    explicit thread(Function&& f, Args&&... args);
    
    • f:任何可调用对象。
    • args:传递给 f 的参数。
  • 构造新对象并将它与执行线程关联。

示例1 函数作为参数

#include <stdio.h>
#include <thread>
#include <chrono>void f1(int n, int& b)
{for (int i = 0; i < 3; ++i) {printf("thread is running\n");++n;++b;std::this_thread::sleep_for(std::chrono::milliseconds(10));}printf("in thread, n is %d, b is %d\n", n, b);
}int main()
{int n = 0;int b = 0;// n 按值传递,b 按引用传递std::thread t1(f1, n, std::ref(b));t1.join();printf("in main, n is %d, b is %d\n", n, b);return 0;
}

示例2 lamba 作为参数

int main()
{std::thread t1([](){for (int i = 0; i < 3; ++i) {printf("thread is running\n");std::this_thread::sleep_for(std::chrono::milliseconds(10));}});t1.join();return 0;
}

示例3 类的成员函数作为参数

#include <stdio.h>
#include <thread>
#include <chrono>class foo {
public:void bar(){for (int i = 0; i < 3; ++i) {printf("thread is running\n");std::this_thread::sleep_for(std::chrono::milliseconds(10));}}
};int main()
{foo f;std::thread t1(&foo::bar, &f);t1.join();return 0;
}

示例4 可调用对象作为参数

#include <stdio.h>
#include <thread>
#include <chrono>class baz
{
public:void operator()(){for (int i = 0; i < 3; ++i) {printf("thread is running\n");std::this_thread::sleep_for(std::chrono::milliseconds(10));}}
};int main()
{baz b;// 调用 baz::operator()std::thread t1(b);t1.join();return 0;
}

示例5 std::function 作为参数

#include <stdio.h>
#include <thread>
#include <chrono>
#include <functional>int main()
{std::function<void(void)> func = [](){for (int i = 0; i < 3; ++i) {printf("thread is running\n");std::this_thread::sleep_for(std::chrono::milliseconds(10));}};std::thread t1(func);t1.join();return 0;
}

更多推荐

c++ 线程使用详解 lamba std::function 传递引用 类成员函数

本文发布于:2023-11-17 04:06:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   详解   函数   成员   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!