C11并发 std::promise<T>

本文介绍了C++中std::promise和std::future类的基本使用方法及如何利用它们实现线程间的同步。通过实例展示了如何设置共享状态的值、获取异常以及如何避免拷贝并使用转移语义。

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

头文件中包含了以下几个类和函数:

Providers 类:std::promise, std::package_task
Futures 类:std::future, shared_future.
Providers 函数:std::async()
其他类型:std::future_error, std::future_errc, std::future_status, std::launch.
std::promise 类介绍

promise 对象可以保存某一类型 T 的值,该值可被 future 对象读取(可能在另外一个线程中),因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。

可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state)

promise 对象是异步 Provider,它可以在某一时刻设置共享状态的值。
future 对象可以异步返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready,然后才能获取共享状态的值。
下面以一个简单的例子来说明上述关系

void print_int(std::future<int>& fut) {
    try {
        std::cout << " fut.get()" << '\n';
        int x = fut.get();
        std::cout << "value: " << x << '\n';
    }
    catch (std::exception& e) {
        std::cout << "[exception caught: " << e.what() << "]\n";
    }
}

int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    std::thread th2(print_int, std::ref(fut));
    Sleep(5000);
    prom.set_value(11);
    th2.join();

    return 0;
}

prom.get_future()通过 get_future 来获取与该 promise 对象相关联的 future 对象

std::future .get()阻塞当前线程 直到有值:std::promise.set_value

例2,反过来,适用socket异步通信中收包同步


#include "stdafx.h"

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
#include <windows.h>
void get_int(std::promise<int>& prom) { 
    try {
                                 // sets failbit if input is not int
        Sleep(5000);
        prom.set_value(123);

    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}


int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();

    std::thread(get_int, std::ref(prom)).detach();  

    std::cout << "value:" << fut.get()<< std::endl;
    return 0;
}

std::promise set_exception实现跨线程异常传递

void get_int(std::promise<int>& prom) { 
    try {
                                 // sets failbit if input is not int
        Sleep(5000);
        throw std::logic_error("merro");
        prom.set_value(123);


    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}


int main()
{
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();

    std::thread(get_int, std::ref(prom)).detach();  

    try
    {
        std::cout << "value:" << fut.get() << std::endl;
    }
    catch (const std::exception& e)
    {
        std::cout << "erro:" << e.what() << std::endl;
    }

    return 0;
}

禁止复制拷贝,用转移语义:


#include "stdafx.h"

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
#include <windows.h>
#include <stdexcept>
#include <vector>
using namespace std;
vector<std::promise<int> > globalArray;
void get_int(std::promise<int>& prom) { 
    try {
                                 // sets failbit if input is not int
        Sleep(1000);
        throw std::logic_error("merro");
        prom.set_value(123);


    }
    catch (std::exception&) {
        prom.set_exception(std::current_exception());
    }
}


int main()
{
    for (int i=0;i<10;i++)
    {
        std::promise<int> prom;
        globalArray.push_back(std::move(prom));
    }



        for (auto &x : globalArray)
        {
            try
            {

                std::thread(get_int, std::ref(x)).detach();
                std::cout << "value:" << x.get_future().get() << std::endl;
            }
            catch (const std::exception& e)
            {
                std::cout << "erro:" << e.what() << std::endl;
            }
        }




    return 0;
}

或者更方便的设计:(注 future .get的时候才会获取异常)


#include "stdafx.h"

#include <iostream>       // std::cin, std::cout, std::ios
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <exception>      // std::exception, std::current_exception
#include <windows.h>
#include <stdexcept>
#include <vector>
#include <memory>
using namespace std;
vector<std::shared_ptr<std::promise<int>> > globalArray;
void get_int(std::shared_ptr<std::promise<int>> prom) {
    try {
                                 // sets failbit if input is not int

        throw std::logic_error("merro");
        prom->set_value(123);


    }
    catch (std::exception&) {
        prom->set_exception(std::current_exception());
    }
}


int main()
{
    for (int i = 0; i < 10; i++)
    {
        auto pprom = std::make_shared<std::promise<int>>();


        globalArray.push_back(pprom);
        try
        {
            std::thread(get_int, pprom).detach();

        }
        catch (const std::exception& e)
        {
            std::cout << "erro0:" << e.what() << std::endl;
        }
    }

    Sleep(1000);

    for (auto &x : globalArray)
    {

        try
        {
            std::cout << "value:" << x->get_future().get() << std::endl;

        }
        catch (const std::exception& e)
        {
            std::cout << "erro:" << e.what() << std::endl;
        }



    }




    return 0;
}

<think>好的,我现在需要把用户提供的C++代码转换成C语言实现同样的功能。首先,我得仔细理解原代码的逻辑,然后考虑C语言中对应的数据结构和函数。 原代码主要做了以下几件事: 1. 读取顾客数量n。 2. 读取n行时间字符串,用std::map统计每个时间出现的次数,同时保持时间有序。 3. 遍历这个有序的map,统计同一秒内的订单数量,并将每秒钟的第一个订单的数量计入免单顾客数。 首先,C语言中没有std::map,所以需要用其他方法来实现有序的存储和统计。考虑到订单时间是有时间顺序的,可能需要先读取所有时间,然后进行排序。统计次数的话,可以用结构体数组来存储时间和对应的次数。 步骤分解: 1. **读取输入**:C中读取输入可以用fgets,但要注意处理换行符。首先读取n,然后读取n行时间字符串。 2. **存储和统计时间**:原代码用map保证了时间的有序性和统计次数。C中需要手动排序,比如用qsort,然后遍历数组统计连续相同时间的次数。 3. **统计免单数量**:遍历排序后的数组,比较当前时间和前一个时间的秒部分(前19个字符),如果不同,则累加该时间的出现次数。 需要注意的问题: - **内存管理**:C中需要预先分配足够的内存来存储所有时间字符串,比如定义一个二维字符数组或者动态分配。 - **排序函数**:需要自定义比较函数来对时间字符串进行排序。 - **统计次数**:原代码的map在插入时自动合并相同键值,而C中需要在排序后手动统计,可能需要在结构体中记录次数。 具体实现思路: 1. 定义一个结构体TimeCount,包含时间字符串和出现次数。 2. 读取所有时间到数组中,然后排序。 3. 遍历排序后的数组,合并相邻相同时间,记录次数到结构体数组中。 4. 再次遍历结构体数组,比较秒部分的变化,累加免单数量。 可能的难点: - 处理输入时的换行符,尤其是混合使用scanf和fgets时,需要清除输入缓冲区。 - 正确实现排序和合并相同时间的逻辑,确保统计正确。 - 内存分配是否足够,避免溢出。 测试案例验证: 例如,输入时间为: 3 2023-01-01 12:00:00.123 2023-01-01 12:00:00.123 2023-01-01 12:00:01.456 排序后相同的时间会被合并,统计时每个秒级单位的第一组会被计入免单数,所以输出应为2(第一个秒有两个订单,第二个秒有一个)。 需要确保在转换过程中逻辑一致,特别是处理时间字符串的前19位作为秒的判断。</think>以下是用C语言实现相同功能的逐步说明及代码: $关键步骤分析$: 1. 输入处理:混合使用scanf和fgets需处理换行符 2. 时间排序:使用qsort实现字典序排序 3. 统计频次:合并相邻相同时间记录 4. 免单计算:比较前19个字符判断是否新秒 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define MAX_CUSTOMERS 100000 #define TIME_LENGTH 26 // 结构体存储时间及其出现次数 typedef struct { char time[TIME_LENGTH]; int count; } TimeEntry; // qsort比较函数 int compare_time(const void *a, const void *b) { return strcmp((const char*)a, (const char*)b); } int main() { int n; scanf("%d", &n); getchar(); // 消耗换行符 // 读取所有时间到临时数组 char times[MAX_CUSTOMERS][TIME_LENGTH]; for (int i = 0; i < n; ++i) { fgets(times[i], TIME_LENGTH, stdin); times[i][strcspn(times[i], "\n")] = '\0'; // 去除换行符 } // 步骤1:排序时间 qsort(times, n, TIME_LENGTH, compare_time); // 步骤2:统计时间频次 TimeEntry entries[MAX_CUSTOMERS]; int entry_count = 0; if (n > 0) { strcpy(entries[0].time, times[0]); entries[0].count = 1; entry_count = 1; } for (int i = 1; i < n; ++i) { if (strcmp(times[i], times[i-1]) == 0) { entries[entry_count-1].count++; } else { strcpy(entries[entry_count].time, times[i]); entries[entry_count].count = 1; entry_count++; } } // 步骤3:计算免单数量 int free_count = 0; char prev_second[20] = ""; // 存储前19个字符 for (int i = 0; i < entry_count; ++i) { char current_second[20]; strncpy(current_second, entries[i].time, 19); current_second[19] = '\0'; if (strcmp(current_second, prev_second) != 0) { free_count += entries[i].count; strcpy(prev_second, current_second); } } printf("%d\n", free_count); return 0; } ``` $实现差异说明$: 1. 内存管理:C版本使用预分配数组,C++使用动态容器 2. 排序方式:C手动实现合并统计,C++依赖std::map自动排序 3. 时间复杂度:均为$O(n\log n)$,但C版本需两次遍历(排序+统计) 4. 字符串处理:C使用strncpy/strcmp,C++使用string类 使用时需注意: 1. 最大顾客数限制(可通过动态内存分配改进) 2. 输入时间格式必须严格符合"YYYY-MM-DD HH:MM:SS.XXX" 3. 依赖C11标准编译(建议使用-std=c11编译选项) 该实现完整还原了原始代码的以下特性: - 按时间有序处理订单 - 精确到秒级的免单判断 - 相同时间的订单合并统计
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值