2

I have some dlls written in Dotnet which I am using to access thousands of binary files. The data is compartmentalized by directories, so as a performance enhancement I thought of using multiple processes or threads to churn through the files.

I have a function, currently part of the main class (requiring self as an argument), this could easily be refactored to a private method.

My first inclination is to use the Multiprocess module, but that doesn't seem to be available for IronPython.

My next thought was to use Task

def __createThreads(self):
    tasks = Array.CreateInstance(Task, 5)
    for idx in range(0, 5):
        tasks.append(Task.Factory.StartNew(self.__doWork, args=(idx,)))

    Task.WaitAll(tasks)

def __doWork(self, idx):

    for index in range (0, idx):
        print "Thread: %d | Index: %d" % (idx, index)

Or to use Thread

def __createThreads(self):
    threads = list()
    for idx in range(0, 5):
        t = Thread(ThreadStart(self.__doWork))
        t.Start()
        threads.append(t)

    while len(threads) > 0:
        time.sleep(.05)
        for t in threads:
            if(not t.IsAlive):
                threads.remove(t)

What I cannot find is a IronPython example of how to pass arguements

4

1 回答 1

1

请注意,您的两个示例并不完全相同。当运行时认为这是一个好主意时,任务版本只会创建/使用实际的并发线程(除非您指定TaskCreationOptions.LongRunning)。您必须决定什么适合您的用例。

将idx参数传递给__doWork函数的最简单方法是使用 lambda 来捕获值和调用。(请注意这个问题中讨论的范围界定问题,这也暗示了引入中间范围的替代解决方案)

tasks.append(Task.Factory.StartNew(lambda idx = idx: self.__doWork(idx)))

附带说明:您必须将任务列表转换为数组才能让 Task.WaitAll 满意。

于 2013-09-09T12:07:59.080 回答