如何在Python中使用线程

0 投票
3 回答
1247 浏览
提问于 2025-04-16 07:51

我想用这个方法来读取17770个文件里的值,然后把它们全部加到一个字典对象里。我的机器有8个核心。

这是代码

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);

3 个回答

0

你觉得使用线程会对这个问题有什么帮助呢?

虽然Python支持多线程,但它的标准版本(CPython)一次只能运行一个线程。所以,即使在多个核心上运行,也很难想象这样会让程序运行得更快。

不过,如果你使用的是JPython或IronPython,这个限制就不适用了。

1

这里有一些很不错的Python库参考资料,适合入门学习。

http://docs.python.org/py3k/library/threading.html

http://docs.python.org/py3k/library/_thread.html

至于如何有效地使用线程,我建议你去网上搜索一下“python线程教程”之类的内容。

4

这里有一个很棒的 multiprocessing 模块。它可以让你把代码并行处理,也就是说可以同时运行多个任务,而不是一个一个地执行。这样可以充分利用你的电脑所有的处理器核心。

一个重要的区别是,进程之间不共享内存;这时候可以用一个队列来帮助处理数据的减少步骤。

撰写回答