首页 \ 问答 \ 如何创建一个新的线程来执行一个Action (How to create a new Thread to execute an Action)

如何创建一个新的线程来执行一个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
更新时间:2022-04-23 21:04

最满意答案

给定一个函数,你可以像这样创建一个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 when f2 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) the LazyComparer 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 ...
  • 使用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函 ...
  • 你可能想要这样的东西: 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提供了延 ...
  • 我建议将每个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 ...
  • 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 ...
  • 您可以使用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 ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。