如何创建一个新的线程来执行一个Action (How to create a new Thread to execute an Action)
标题几乎说明了这一点。 我有一些需要在新线程上运行的方法,并且因为在创建线程之前所有的代码都差不多,所以我想我会创建一个可以作为我需要调用的Action的参数的函数。
问题是,我还没有找到如何告诉线程它需要执行该操作。 这甚至有可能吗? 以下是我想要做的一些示例代码。
private void ExecuteInBiggerStackThread(Action<Helper> action, Parameters parms) { ParameterizedThreadStart operation = new ParameterizedThreadStart(action);// here's the mess Thread bigStackThread = new Thread(operation, 1024 * 1024); bigStackThread.Start(parms); bigStackThread.Join(); }
问候,
西巴The title pretty much says it. I have some methods that need to run on a new thread and since all the code before creating the thread is pretty much the same, I thought I would create a function that could take as a parameter the Action I need to invoke.
Problem is, I have not found how to tell the thread that it needs to execute the Action. Is that even possible? Here's a little sample code of what I'm trying to do.
private void ExecuteInBiggerStackThread(Action<Helper> action, Parameters parms) { ParameterizedThreadStart operation = new ParameterizedThreadStart(action);// here's the mess Thread bigStackThread = new Thread(operation, 1024 * 1024); bigStackThread.Start(parms); bigStackThread.Join(); }
Regards,
seba
原文:https://stackoverflow.com/questions/3290859
最满意答案
给定一个函数,你可以像这样创建一个LazyComparer类:
def lazy_func(func): class LazyComparer(object): def __init__(self, x): self.x = x def __lt__(self, other): return func(self.x) < func(other.x) def __eq__(self, other): return func(self.x) == func(other.x) return lambda x: LazyComparer(x)
要从多个函数中创建一个懒惰的关键函数,您可以创建一个实用程序函数:
def make_lazy(*funcs): def wrapper(x): return [lazy_func(f)(x) for f in funcs] return wrapper
一起他们可以像这样使用:
def countcalls(f): "Decorator that makes the function count calls to it." def _f(*args, **kwargs): _f._count += 1 return f(*args, **kwargs) _f._count = 0 return _f @countcalls def g(x): return x @countcalls def f1(x): return 0 @countcalls def f2(x): return x def report_calls(*funcs): print(' | '.join(['{} calls to {}'.format(f._count, f.func_name) for f in funcs])) L = range(10)[::-1] L.sort(key=make_lazy(f1, g)) report_calls(f1, g) g._count = 0 L.sort(key=make_lazy(f2, g)) report_calls(f2, g)
这产生了
18 calls to f1 | 36 calls to g 36 calls to f2 | 0 calls to g
上面的@countcalls装饰器用于确认当
f1
返回很多关系时,调用g
来中断关系,但是当f2
返回不同的值时,g
不会被调用。
NPE的解决方案在
Key
类中增加了记忆。 通过上面的解决方案,您可以在LazyComparer
类的外部(独立于)添加记忆:def memo(f): # Author: Peter Norvig """Decorator that caches the return value for each call to f(args). Then when called again with same args, we can just look it up.""" cache = {} def _f(*args): try: return cache[args] except KeyError: cache[args] = result = f(*args) return result except TypeError: # some element of args can't be a dict key return f(*args) _f.cache = cache return _f L.sort(key=make_lazy(memo(f1), memo(g))) report_calls(f1, g)
这样可以减少对
g
的呼叫:10 calls to f1 | 10 calls to g
Given a function, you could create a LazyComparer class like this:
def lazy_func(func): class LazyComparer(object): def __init__(self, x): self.x = x def __lt__(self, other): return func(self.x) < func(other.x) def __eq__(self, other): return func(self.x) == func(other.x) return lambda x: LazyComparer(x)
To make a lazy key function out of multiple functions, you could create a utility function:
def make_lazy(*funcs): def wrapper(x): return [lazy_func(f)(x) for f in funcs] return wrapper
And together they could be used like this:
def countcalls(f): "Decorator that makes the function count calls to it." def _f(*args, **kwargs): _f._count += 1 return f(*args, **kwargs) _f._count = 0 return _f @countcalls def g(x): return x @countcalls def f1(x): return 0 @countcalls def f2(x): return x def report_calls(*funcs): print(' | '.join(['{} calls to {}'.format(f._count, f.func_name) for f in funcs])) L = range(10)[::-1] L.sort(key=make_lazy(f1, g)) report_calls(f1, g) g._count = 0 L.sort(key=make_lazy(f2, g)) report_calls(f2, g)
which yields
18 calls to f1 | 36 calls to g 36 calls to f2 | 0 calls to g
The @countcalls decorator above is used to connfirm that when
f1
returns a lot of ties,g
is called to break the ties, but whenf2
returns distinct values,g
does not get called.
NPE's solution adds memoization within the
Key
class. With the solution above, you could add memoization outside (independent of) theLazyComparer
class:def memo(f): # Author: Peter Norvig """Decorator that caches the return value for each call to f(args). Then when called again with same args, we can just look it up.""" cache = {} def _f(*args): try: return cache[args] except KeyError: cache[args] = result = f(*args) return result except TypeError: # some element of args can't be a dict key return f(*args) _f.cache = cache return _f L.sort(key=make_lazy(memo(f1), memo(g))) report_calls(f1, g)
which results in fewer calls to
g
:10 calls to f1 | 10 calls to g
相关问答
更多-
给定一个函数,你可以像这样创建一个LazyComparer类: def lazy_func(func): class LazyComparer(object): def __init__(self, x): self.x = x def __lt__(self, other): return func(self.x) < func(other.x) def __eq__(self, other): ...
-
假设您的指数是唯一的,这是一种方法。 您可以初始化新列表,只需将元素插入正确的位置即可。 def magic_rearrange(l1): l2 = [None] * len(l1) for i in l1: l2[i[1]] = i return l2 还有一个演示: >>> l = [('item1',1), ('item0',0), ('item2',2), ('item4',4), ('item3',3)] >>> magic_rearrange(l) [( ...
-
更新compateString方法,如下所示: 你需要比较id的每一步。 public static int compareString(String str1, String str2){ String subString = str1.substring(str1.indexOf("##")+3, str1.length()); String subString1 = str2.substring(str2.indexOf("##")+3, str2.length()); S ...
-
使用functools.cmp_to_key ,这将保证与比较函数相同的排序行为。 可以在Python的Sorting How To文档中找到此函数的源代码。 Use functools.cmp_to_key, this will guarantee the same sorting behavior as your compare function. The source for this function can be found on Python's Sorting How To document. ...
-
尝试: // The variable list is sorted into another list called sortedList sortedList = list.OrderBy(x => x.SomeIntegerData.ContainsKey("key-that-is-not-in-every-item")?x.SomeIntegerData["key-that-is-not-in-every-item"]:null).ToList(); Try: // The variable li ...
-
按除法值排序列表(Sorting list by value of division)[2022-09-17]
使用sorted()和key ,如: >>> a = [[10,5],[9,3],[16,2],[8,8]] >>> sorted(a, key= lambda x: x[0]/x[1]) [[8, 8], [10, 5], [9, 3], [16, 2]] 来自Docs, key specifies a function of one argument that is used to extract a comparison key from each list element 这里, lambda函 ... -
根据键排序python列表(sorting python list based on key)[2023-04-19]
你可能想要这样的东西: my_entries_list.sort(key=lambda v: datetime.datetime.combine(v.created_date, v.created_time)) 传递datetime.datetime.combine(created_date, created_time)尝试立即调用combine和break,因为created_date和created_time不可用作局部变量。 lambda提供了延 ... -
Python - 排序列表(Python - Sorting Lists)[2023-06-16]
我建议将每个lsDataSorted块包装到一个自定义类中,该类将根据您的复杂条件强制进行比较。 例如: import functools @functools.total_ordering class Compare(object): def __init__(self, chunk): self.x = chunk[7], int(chunk[5]) - int(chunk[6]), chunk[5] self.y = chunk[0] def __eq ... -
按键排序列表(Sorting a list by a key)[2022-04-10]
msg = ['BC', 'DE', 'DE', 'DA', 'FD', 'DD', 'BE', 'FE', 'DA', 'EA', 'FE', 'BC', '12'] key = 'CODE' # 'flatten' the message msg = ''.join(msg) key_length = len(key) #create a dictionary with the letters of the key as the keys #use a slice to create the value ... -
在python中排序列表(sorting a list in python)[2022-08-21]
您可以使用itemgetter作为函数来获取值以对列表进行排序。 然后要获得排名,您可以使用enumerate 。 from operator import itemgetter score_list = score() score_list.sort(key=itemgetter(2), reversed=True) # sort list descending by third element for i, values in enumerate(score_list): print(valu ...