2014-11-03 18 views
1

我想在Python中使用multiprocessing模塊編碼並行代碼,我想知道一種方法來本地知道哪個CPU正在計算,但我只知道multiprocessing.CPU_count()瞭解總CPU內核。Python多處理:知道線程/ CPU編號

我正在尋找的等效:

omp_get_thread_num() 
在C++中的OpenMP

Python.multiprocessing中是否有這樣的方法?

+0

你可以閱讀多處理的文件在[這裏](https://docs.python.org/2/library/multiprocessing.html)來查看它是否存在。 – zamk 2014-11-03 13:44:42

回答

5

這是不平凡的檢索過程是在運行的CPU(如果可能的話),但如果你:

  • 啓動相同數量的過程,因爲有可用的CPU,如multiprocessing.CPU_count()報道,如大多數應用程序一樣;

  • 假設每個進程都運行在不同的CPU內核中,正如使用multiprocessing模塊時所預期的那樣;

然後你就可以「欺騙」,並給每個進程的唯一,將確定其CPU核心! :)

for i in xrange(multiprocessing.CPU_count()): 
    mp = multiprocessing.Process(target=foo, args=(bar,), name=i).start() 

,然後檢索它的工人函數內部產生了在子:

print "I'm running on CPU #%s" % multiprocessing.current_process().name 

official documentation

multiprocessing.current_process().name

The process’s name. 

The name is a string used for identification purposes only. It has no semantics. 
Multiple processes may be given the same name. 
The initial name is set by the constructor. 
+0

謝謝你,我選擇了一個類似的解決方案,我將索引'i'作爲參數或'i == 0'作爲布爾值,因此只有一個進程的值爲True,只有這個進程正在輸出在屏幕上給我例如進度信息(避免重載)。我以爲'multiprocessing'具有與C++ OpenMP相同的變量,但不是,但是在這種情況下,避開這個障礙並不難。 – 2014-11-24 12:33:04