Per*_*ion 3 c++ macos asynchronous future
我正在尝试构建一个异步应用程序以允许并行处理大型列表,在通过谷歌搜索学习 C++ 两天后,我从以下代码中找到了标题错误:
//
// main.cpp
// ThreadedLearning
//
// Created by Andy Kirk on 19/01/2016.
// Copyright © 2016 Andy Kirk. All rights reserved.
//
#include <iostream>
#include <thread>
#include <vector>
#include <chrono>
#include <future>
typedef struct {
long mailing_id;
char emailAddress[100];
} emailStruct ;
typedef struct {
long mailing_id = 0;
int result = 0;
} returnValues;
returnValues work(emailStruct eMail) {
returnValues result;
std::this_thread::sleep_for(std::chrono::seconds(2));
result.mailing_id = eMail.mailing_id;
return result;
}
int main(int argc, const char * argv[]) {
std::vector<emailStruct> Emails;
emailStruct eMail;
// Create a Dummy Structure Vector
for (int i = 0 ; i < 100 ; ++i) {
std::snprintf(eMail.emailAddress,sizeof(eMail.emailAddress),"user-%d@email_domain.tld",i);
eMail.mailing_id = i;
Emails.push_back(eMail);
}
std::vector<std::future<returnValues>> workers;
int worker_count = 0;
int max_workers = 11;
for ( ; worker_count < Emails.size(); worker_count += max_workers ){
workers.clear();
for (int inner_count = 0 ; inner_count < max_workers ; ++inner_count) {
int entry = worker_count + inner_count;
if(entry < Emails.size()) {
emailStruct workItem = Emails[entry];
auto fut = std::async(&work, workItem);
workers.push_back(fut);
}
}
std::for_each(workers.begin(), workers.end(), [](std::future<returnValues> & res) {
res.get();
});
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
真的不确定我做错了什么,并且在搜索中找到了有限的答案。如果相关,它在 OSX 10 和 XCode 7 上。
该future班有它的拷贝构造函数删除,因为你真的不希望有它的多个副本。
要将其添加到向量中,您必须移动它而不是复制它:
workers.push_back(std::move(fut));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3256 次 |
| 最近记录: |