2010-11-30 21 views
0

我想用它读取17770个文件中的值,并将它们全部添加到一个字典对象中。我有一个8核心的机器。如何在python中使用线程

这是代码

def run_item_preprocess(): 
    scores = {}; 
    for i in range(1,17771): 
     filename1 = "x_" + str(i) + ".txt"; 
     lines1 = open(filename1).readlines(); 
     Item1 = {}; 
     for line in lines1: 
      tokens = line.split(','); 
      Item1[int(tokens[1])] = int(tokens[2]); 
     for j in range(1,17771): 
      if j == i: 
       continue; 
      filename2 = "x_" + str(i) + ".txt"; 
      lines2 = open(filename2).readlines(); 
      Item2 = {}; 
      for line in lines2: 
       tokens = line.split(','); 
       u = int(tokens[1]); 
       r = int(tokens[2]); 
       if u in Item1: 
        Item2[u] = r; 
      if i not in scores: 
       scores[i] = {}; 
      scores[i]= (s(Item1,Item2),j); 
+0

我在找谁可以帮助我......我发布了我的代码 – turbonerdo 2010-12-01 00:10:58

+0

我看到这个错误吗?您正在尝试打开每个17770个文件17770次? – 2010-12-01 00:16:04

+3

在考虑使它在多个线程中运行之前,您需要确保代码作为单个线程正确运行。我严肃地怀疑这段代码是否做你想做的事。 (315772900文件读取?) – 2010-12-01 00:17:31

回答

4

这是美妙的multiprocessing模块。它可以让你并行化代码,使用进程而不是线程。这将使用所有内核。

一个重要的区别是进程不共享内存;队列将有助于减少步骤。

0

你认为使用线程会对此有所帮助吗?

虽然Python支持线程化,但标准实现(CPython)执行only one thread at a time。因此很难看出,即使在多核上,这也会使进程运行得更快。

(如果你使用了JPython或IronPython的,不过,这种限制并不适用。)