我要执行大量任务,并通过生成器提供结果。但是,使用ProcessPoolExecutor和as_completed将贪婪地评估结果并将其全部存储在内存中。在生成器中存储了一定数量的结果之后,是否有一种方法可以阻止?
我最近碰到过这个:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> //sort function
#include <functional> //functions utilities
#include <random> //random numbers generation
using namespace std;
default_random_engine generator;
uniform_int_distribution<int> distribution(0,9999);
auto randomer = bind(distribution, generator);
struct Test_struct {
string ord_as_string;
int ord;
Test_struct() :
ord(randomer()),
ord_as_string(to_string(ord))
{}
};
int main() {
vector<Test_struct> my_vector;
for(int i = 0; i < 100; ++i) my_vector.push_back(Test_struct());
for(auto& e: my_vector)
cout << e.ord_as_string << " -> " << e.ord << endl;
}
Run Code Online (Sandbox Code Playgroud)
Wich打印以下序列:
142 -> 0
0 -> …Run Code Online (Sandbox Code Playgroud) 我有 2Vec个:
let x = vec!['1', '2', '3'];
let y = vec!['a', 'b', 'c'];
Run Code Online (Sandbox Code Playgroud)
现在我想使用迭代器来创建一个像这样的新 vec ['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']。我能怎么做?
我试图绕过从模块导入,所以在我__init__.py可以注入这样的代码:
globals().update(
{
"foo": lambda: print("Hello stackoverflow!")
}
)
Run Code Online (Sandbox Code Playgroud)
所以,如果我这样做,import mymodule我就能打电话mymodule.foo.这是一个简单的概念,对于此目的无用,因为您实际上只能定义foo.所以,想法是修改globals模块字典,所以万一它找不到函数foo它会去任何地方我可以注入代码,为此我试过:
from importer import load #a load function to search for the code
from functools import wraps
def global_get_wrapper(f):
@wraps(f)
def wrapper(*args):
module_name, default = args
res = f(*args)
if res is None:
return load(module_name)
return res
return wrapper
globals().get = global_get_wrapper(globals().get) # trying to substitute get method
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误:
AttributeError: 'dict' object attribute 'get' is read-only
Run Code Online (Sandbox Code Playgroud)
我的另一个想法是将可用的函数,类等名称预加载到模块字典中,然后懒洋洋地加载它们.
我没有想法来完成这个,我不知道这是否可能.我应该去写我自己的python导入器吗?还是有其他我无法思考的可能性?提前致谢.
我找到了一些无法理解的东西.我认为它应该与函数堆栈和一些未定义的行为有关.
假设我有一个功能工厂模板(傻一个):
template <unsigned int N=10>
std::function<int&&(const int& n)> build_add_function() {
return [](const int& n) -> int&& {std::move(n+N);};
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,它缺少非void函数的return语句,因此编译器向我发出警告......奇怪的是它"按预期"工作
int main() {
auto foo = build_add_function();
std::cout << foo(10);
}
Run Code Online (Sandbox Code Playgroud)
主要输出: 20
当然,为了修复代码,我添加了return语句,它给了我一个分段错误
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Run Code Online (Sandbox Code Playgroud)
我对我正在做的事情有一些误解,但我无法理解它.有人会向我解释这里发生了什么吗?我正在使用gcc版本8.0.1
编辑:刚刚测试gcc 4.8.1并使用return语句按预期工作,没有编译错误.
它是编译器的东西吗?
我正在尝试在中创建一个备忘录功能Rust。问题是获取缓存的可变引用时HashMap。我对类型系统仍然没有信心,我有点挣扎。
use std::collections::HashMap;
use std::hash::Hash;
fn memoize<A, B, F>(f: F, cache: &'static HashMap<A, B>) -> impl Fn(A) -> B
where
A: Eq + Hash + Copy,
B: Clone,
F: Fn(A) -> B,
{
move |value: A| {
if !cache.contains_key(&value) {
cache.insert(value, f(value.clone()));
}
let res = cache.get(&value).unwrap();
res.clone()
}
}
Run Code Online (Sandbox Code Playgroud)
错误是:
use std::collections::HashMap;
use std::hash::Hash;
fn memoize<A, B, F>(f: F, cache: &'static HashMap<A, B>) -> impl Fn(A) -> B
where
A: Eq + Hash + Copy, …Run Code Online (Sandbox Code Playgroud) 从源头看:
// Listen creates a TLS listener accepting connections on the
// given network address using net.Listen.
// The configuration config must be non-nil and must include
// at least one certificate or else set GetCertificate.
func Listen(network, laddr string, config *Config) (net.Listener, error) {
if config == nil || (len(config.Certificates) == 0 && config.GetCertificate == nil) {
return nil, errors.New("tls: neither Certificates nor GetCertificate set in Config")
}
l, err := net.Listen(network, laddr)
if err != nil {
return …Run Code Online (Sandbox Code Playgroud) 我的意思是,如果 2 个对象在某些属性上重叠,是否有办法尝试匹配所有属性?例如:
use serde::{Serialize, Deserialize};
use serde_json; // 1.0.47; // 1.0.104
#[derive(Serialize, Deserialize, Debug)]
pub struct A {
pub item_1: i32,
pub item_2: i32,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct B {
pub item_1: i32,
pub item_2: i32,
pub item_3: i32,
}
fn main() {
let json_data = r#"{"item_1" : 10, "item_2" : 100, "item_3" : 1000}"#;
if let Ok(data) = serde_json::from_str::<A>(json_data) {
println!("{:?}", data);
} else if let Ok(data) = serde_json::from_str::<B>(json_data) {
println!("{:?}", data);
}
} …Run Code Online (Sandbox Code Playgroud) 让我们说:
data Data a b c = Build (a,b,c) deriving Show
foo :: Data a b c -> Data a b c
foo d = d
main = print $ foo $ Build (1, 1, "a")
Run Code Online (Sandbox Code Playgroud)
有没有办法避免a b c每次使用数据类型的写入?
使用类型,如:
foo :: Data -> Data
foo d = d
Run Code Online (Sandbox Code Playgroud) 我一直在研究一个函数,它将使用Rust和线程将一堆文件从源复制到目标.我在线程共享迭代器时遇到了一些麻烦.我还不习惯借用系统:
extern crate libc;
extern crate num_cpus;
use libc::{c_char, size_t};
use std::thread;
use std::fs::copy;
fn python_str_array_2_str_vec<T, U, V>(_: T, _: U) -> V {
unimplemented!()
}
#[no_mangle]
pub extern "C" fn copyFiles(
sources: *const *const c_char,
destinies: *const *const c_char,
array_len: size_t,
) {
let src: Vec<&str> = python_str_array_2_str_vec(sources, array_len);
let dst: Vec<&str> = python_str_array_2_str_vec(destinies, array_len);
let mut iter = src.iter().zip(dst);
let num_threads = num_cpus::get();
let threads = (0..num_threads).map(|_| {
thread::spawn(|| while let Some((s, d)) = iter.next() {
copy(s, d); …Run Code Online (Sandbox Code Playgroud)