Python多个进程不会循环(Python multiple processes do not loop on for)

我正在研究几种算法的实现,以计算图上的最短路径。

我已经设法顺序实现了Dijkstra的算法,现在我正在尝试通过Python的多处理模块来优化我的算法。

整个代码都有效。 我在这里要做的是:

  • 首先用nb_cpu = mp.cpu_count()来检查我可以处理多少cpus
  • 然后相应地划分我在图表中的所有节点
  • 最后调用方法subprocess_dijkstra ,它应该为每个节点计算dijkstra算法,它作为一个参数给出(这个想法是每个进程只需要为图的一小部分计算算法)。

当我运行我的脚本(从main.py文件中调用我只是根据我的需要格式化数据)时,我有4个进程正在启动。

但是,它们似乎不在subprocess_dijkstra for node in nodes定义的for node in nodes循环中执行for node in nodes

每个进程只计算一次代码,然后无限期地暂停...

这是我在Python下进行多处理的第一次尝试,所以我可能错过了一个细节。 有人有想法吗?

当我中断脚本时,python告诉我中断发生在p.join()行上。

感谢有人帮助我:)

这是我的代码:

import multiprocessing as mp

def subprocess_dijkstra(do_print, nodes, tab_contenu, tab_distances):
    tab_dist_initial = dict(tab_distances)
    tab_dist = dict()
    for node in nodes:
        visited_nodes = list()
        tab_dist = dict(tab_dist_initial)
        dmin = -1
        resultat = ""
        filename = "dijkstra"+str(node)+".txt"

        if do_print:
            dt = open(filename, 'w')
            tab_dist[node] = 0

            """Ligne de résultat initiale"""
            for valeur in tab_dist.values():
                resultat += str(valeur)
                resultat += " "
            resultat += "\n"

            dt.write(resultat)

        while len(visited_nodes) != len(tab_contenu):
            """ On se place sur le noeud non visité qui a la distance minimale de notre départ """
            for cle, valeur in tab_dist.items():
                if cle not in visited_nodes:
                    if dmin ==-1 or valeur<dmin:
                        dmin = valeur
                        node = cle


            """ On vérifie que le noeud n'a pas déjà été visité """
            if (node not in visited_nodes):
                """ On regarde les fils de ce noeud et la longueur des arcs"""
                for cle,valeur in tab_contenu[node].items():
                    tab_dist[cle] = min(tab_dist[cle], tab_dist[node]+valeur)

                visited_nodes.append(node)

                if do_print:
                    resultat = ""
                    """ Ligne de résultat """
                    for valeur in tab_dist.values():
                        resultat += str(valeur)
                        resultat += " "
                    resultat += "\n"

                    dt.write(resultat)

        if do_print:
            dt.close()


def main(do_print,donnees):

    tab_contenu = donnees[1]
    nb_nodes = int(donnees[0])
    tab_distances = {x: float('inf') for x in range(nb_nodes)}
    args=[(do_print, x, tab_contenu, tab_distances) for x in range(nb_nodes)]
    nb_cpu = mp.cpu_count()


    pool = mp.Pool(processes = nb_cpu)
    pool.starmap(subprocess_dijkstra, args)
    pool.close()
    pool.join()

I'm working on the implementation of several algorithms to compute shortest paths on graphs.

I have managed to implement Dijkstra's algorithm sequentially and I'm now trying to optimize my algorithm through the multiprocessing module of Python.

As a whole the code works. What I am trying to do here is :

  • First to check how many cpus I can work on with nb_cpu = mp.cpu_count()
  • Then dividing all the nodes I have in my graph accordingly
  • Finally calling the method subprocess_dijkstra that should compute the dijkstra algorithm for each of the nodes it is given as an argument (the idea being that each process only has to compute the algorithm for a smaller part of the graph).

When I run my script (called from a main.py file where I just format the data to suit my needs), I have 4 processes launched as I should.

However, they do not seem to execute the for node in nodes loop defined in subprocess_dijkstra.

Each process only computes the code once and then they go on hold indefinitely...

It is my first attempt at multiprocessing under Python so I may have missed a detail. Does anybody have an idea ?

When I interrupt the script, python tells me that the interruption takes place on the p.join() line.

Thanks to anyone helping me :)

Here is my code :

import multiprocessing as mp

def subprocess_dijkstra(do_print, nodes, tab_contenu, tab_distances):
    tab_dist_initial = dict(tab_distances)
    tab_dist = dict()
    for node in nodes:
        visited_nodes = list()
        tab_dist = dict(tab_dist_initial)
        dmin = -1
        resultat = ""
        filename = "dijkstra"+str(node)+".txt"

        if do_print:
            dt = open(filename, 'w')
            tab_dist[node] = 0

            """Ligne de résultat initiale"""
            for valeur in tab_dist.values():
                resultat += str(valeur)
                resultat += " "
            resultat += "\n"

            dt.write(resultat)

        while len(visited_nodes) != len(tab_contenu):
            """ On se place sur le noeud non visité qui a la distance minimale de notre départ """
            for cle, valeur in tab_dist.items():
                if cle not in visited_nodes:
                    if dmin ==-1 or valeur<dmin:
                        dmin = valeur
                        node = cle


            """ On vérifie que le noeud n'a pas déjà été visité """
            if (node not in visited_nodes):
                """ On regarde les fils de ce noeud et la longueur des arcs"""
                for cle,valeur in tab_contenu[node].items():
                    tab_dist[cle] = min(tab_dist[cle], tab_dist[node]+valeur)

                visited_nodes.append(node)

                if do_print:
                    resultat = ""
                    """ Ligne de résultat """
                    for valeur in tab_dist.values():
                        resultat += str(valeur)
                        resultat += " "
                    resultat += "\n"

                    dt.write(resultat)

        if do_print:
            dt.close()


def main(do_print,donnees):

    tab_contenu = donnees[1]
    nb_nodes = int(donnees[0])
    tab_distances = {x: float('inf') for x in range(nb_nodes)}
    args=[(do_print, x, tab_contenu, tab_distances) for x in range(nb_nodes)]
    nb_cpu = mp.cpu_count()


    pool = mp.Pool(processes = nb_cpu)
    pool.starmap(subprocess_dijkstra, args)
    pool.close()
    pool.join()

原文:https://stackoverflow.com/questions/29447447
2022-06-15 06:06

满意答案

移动上传的文件后,尝试执行以下操作:

@chmod($path ."/" . $_FILES["file"]["name"], 0777);

或者其他的东西。 您可能希望将权限更改为更好的内容。


After you move the uploaded file, try doing:

@chmod($path ."/" . $_FILES["file"]["name"], 0777);

or something. You might want to change the permissions to something better.

相关问答

更多

无法使用php从目录中删除文件(Can Not delete a file from directory using php)

删除单引号 - 使用 unlink($dir); 代替 unlink('$dir'); remove the single quotes - use unlink($dir); instead of unlink('$dir');

Linux目录权限读写但不删除(Linux directory permissions read write but not delete)

在目录上设置粘贴位置可能就够了。 用户将能够删除他们拥有的任何文件,但不能删除其他用户。 这可能足以满足您的用例。 在大多数系统上,/ tmp以这种方式设置(/ tmp设置为1777) chmod 1775 /控制 但是,如果您想要更多的控制,则必须在有问题的文件系统上启用ACL。 在/ etc / fstab中,将acl附加到标志: /dev/root / ext3 defaults,acl 1 1 然后可以使用set...

对于使用PHP副本创建的文件,无法更改FTP的权限(Can not change permissions on FTP for files created with PHP copy)

PHP脚本与通过FTP登录的用户不同。 使用另一个php脚本更改文件的permisions或通过SSH以root身份登录。 PHP script is a different user than the one that is logging in through FTP. Either change the permisions of the file using another php script or log in as root through SSH.

无法删除使用PHP创建的目录或文件(也称为权限地狱)(Cannot delete directory or files created with PHP (a.k.a permissions hell))

移动上传的文件后,尝试执行以下操作: @chmod($path ."/" . $_FILES["file"]["name"], 0777); 或者其他的东西。 您可能希望将权限更改为更好的内容。 After you move the uploaded file, try doing: @chmod($path ."/" . $_FILES["file"]["name"], 0777); or something. You might want to change the permissions...

PHP和权限(PHP & Permissions)

是的,php可以更改文件的所有权。 使用chown($file, $user) 。 您可以编写一个简单的递归脚本来使用chown更改每个文件的所有者。 Yeah, php can change ownership of a file. Use chown($file, $user). You could write a simple recursive script to change owner for each file using chown.

修改php脚本创建的文件的权限(modify permissions for files created by php script)

尝试chmod功能。 例如chmod("/somedir/somefile", 0755) Try chmod function. For example chmod("/somedir/somefile", 0755)

PHP:创建文件并保留文件权限(PHP: Creating files and preserving file permissions)

如果您通过执行以下操作运行Linux,则可以在文件系统级别解决此问题: chown support:apache foo chmod 775 foo chmod g + s foo 其中foo是保存文件的文件夹。 现在所有(新创建的)文件都应该由support支持:apache。 如果确保将文件创建为664,则两个位置都可以读/写它。 这不是解决问题的唯一(也许甚至不是最好的)方法,但它可能是最简单的方法。 You can solve this at the file system level i...

PHP无法删除目录(PHP cannot delete directory)

[编辑]只能删除空目录。 尝试: <?php //recursively remove a directory function rrmdir($dir) { foreach(glob($dir . '/' . '*') as $file) { if(is_dir($file)){ rrmdir($file); }else{ unlink($file); } } rmdir($d...

如何使用php删除目录中的旧文件(how to delete old files in a directory using php)

使用PHP备份进行备份后,您将遍历目录,然后删除最旧的备份文件: $files = glob('backupfolder/*.bak'); if(count($files) > 10) foreach($files as $file) if(time() - filectime($file) > 10 * 24 * 60 * 60) unlink($file); After making the backup with the PHP backup you loop th...

PHP fopen()创建没有权限修改文件的文件(PHP fopen() creating file without permissions to modify it)

事实证明,有问题的目录安装在不支持Linux文件权限的文件系统上。 It turns out the directory in question was mounted on a file system that doesn't support linux file permissions.

相关文章

更多

《虚拟机系统与进程的通用平台》(Virtual Machines: Versatile Platforms for Systems and Processes)扫描版[PDF]

中文名: 虚拟机系统与进程的通用平台 原名: Virtual Machines: Versati ...

探索 Python,第 1 部分: Python 的内置数值类型

Python 编程语言具有很高的灵活性,它支持多种编程方法,包括过程化的、面向对象的和函数式的。但最重 ...

HDFS patch前后Ganglia看到running processes变化的分析

Ganglia running processes是怎么算出来的?ganglia是通过 cat /pr ...

Python资源索引 【转载】

原文地址:http://blog.chinaunix.net/uid-25525723-id-3630 ...

python字典操作

python里的字典就像java里的HashMap,以键值对的方式存在并操作,其特点如下:通过键来存取 ...

python下载pps视频

思路 视频播放地址提取 直接解析一下原网页的源文件,利用正则就可以得到所有视频的播放地址,下面的 ...

python top project of 2013

Hi Pythonistas! 测试和调试 Testing &amp; Debuggi ...

Python:渗透测试开源项目【源码值得精读】

sql注入工具:sqlmap DNS安全监测:DNSRecon 暴力破解测试工具:patator XS ...

【转帖】Python 资源索引

原文地址:http://wiki.woodpecker.org.cn/moin/ObpLovelyPy ...

(转)Python WEB应用框架纵览

原文链接:http://wiki.woodpecker.org.cn/moin/PyWebFrameL ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本