C++ thread common

这是一个C++示例,展示了如何使用std::thread创建并管理多个线程。示例中定义了task()、f1()和f2()三个线程任务,f2()通过引用传递参数并修改其值。程序创建了四个线程,t2和t4分别调用f1和f2,t3被移到t4后执行。最后输出n的最终值,演示了线程间的同步和数据共享。

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

#include "iostream"
#include "thread"
#include <utility>
#include <chrono>
#include <functional>
#include <atomic>

using namespace std;

void task()
{
    cout << "thread" <<endl;
}

void f1(int n)
{
    for(int i = 0; i < 5; i++)
    {
        cout << "f1 thread " << n <<endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}

void f2(int& n)
{
    for(int i = 0; i < 5; i++)
    {
        cout << "f2 thread  executing " << endl ;
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}


int main()
{
    int n = 0;
    thread t1;
    thread t2(f1, n+ 1);
    thread t3(f2, std::ref(n));
    thread t4(std::move(t3));// t4 is now running f2(). t3 is no longer a thread

    t2.join();
    t4.join();

    cout << "final value of n is " << n << endl;
    getchar();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值