Cpp 11 / 线程库 / 可以做为线程的执行对象有哪些?

本文通过示例代码展示了C++中不同类型的函数如何被用作线程目标,包括普通函数、仿函数和lambda表达式。每个函数类型在创建线程时有不同的使用方式,但都能实现并行执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

答案

普通函数、仿函数、lambda 表达式

栗子

#include <iostream>
#include <thread>

class CTest
{
public:
    //  仿函数。
    void operator()()
    {
        std::cout << " () " << std::endl;
        return;
    }
};
//  普通函数。
void func()
{
    std::cout << " func " << std::endl;
    return;
}

int main()
{
    CTest test;
    std::thread thread_1(func);
    std::thread thread_2(test);
    //  lambda 表达式。
    auto other = []{
        std::cout << " other " << std::endl;
        return;
    };
    std::thread thread_3(other);
    thread_1.join();
    thread_2.join();
    thread_3.join();

    return 0;
}

结果(不一定)

 func  ()
 other

 

(SAW:Game Over!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值