眾所周知,Python代碼中有一個threading模塊,可以創建多線程,但是在這種模式下創建的多線程並不能將多核利用起來,所有由這種模式下創建的線程最多只能共享一個CPU核,所以在有些場景下,我們需要將一個作業分配給一個獨立的線程,並且每個獨立的線程可以使用不同的CPU核資源,做到真正的並發執行。
如何實現呢?這里有一個辦法是通過調用一個C庫函數來實現,在C庫中再調用標准的pthread_create函數來實現,參考代碼如下:
- C庫函數
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h>
void myThread(void arg)
{
while (1);
}
void createThread(void)
{
int err;
pthread_t tid;
err = pthread_create(&tid, NULL, myThread, NULL);
if (err != 0) {
printf("create thread failed!\n");
return;
}
return;
}
編譯成動態庫:
$ gcc -fPIC -shared -o libfoo.so foo.c
- 在Python中調用,實現真正的多線程
代碼如下:
#-*- coding=utf-8 -*- from ctypes import * import time
lib = CDLL("./libfoo.so", RTLD_GLOBAL)
create_thread = lib.createThread
#create_thread.argtypes = [c_void]
#create_thread.restype = c_void
if name == 'main':
create_thread()
create_thread()
while True:
print 'I am in main thread!'
time.sleep(2)
運行起來后,查看CPU占用率:
hank@hank-desktop:~/Study/Python/CallC2$ top top - 10:33:27 up 2:06, 3 users, load average: 0.31, 0.08, 0.07 Tasks: 159 total, 1 running, 158 sleeping, 0 stopped, 0 zombie %Cpu0 :100.0 us, 0.0 sy, 0.0 ni, 0.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st %Cpu1 : 0.0 us, 0.0 sy, 0.0 ni,100.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st %Cpu2 : 0.3 us, 0.0 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st %Cpu3 :100.0 us, 0.0 sy, 0.0 ni, 0.0 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem: 8166744 total, 1696620 used, 6470124 free, 280708 buffers KiB Swap: 0 total, 0 used, 0 free. 731816 cached Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2625 hank 20 0 51404 7616 4824 S 199.8 0.1 0:17.52 python
1035 daemon 20 0 517408 8136 7144 S 0.3 0.1 0:25.53 CodeMeterLin
2628 hank 20 0 29152 3324 2804 R 0.3 0.0 0:00.01 top
可以看到在C庫中創建的兩個線程(while無限循環)分別消耗掉了兩個獨立的CPU核,這也就驗證了可以做到真正並發的目的。