Python代码中有一个threading模块,可以创建多线程,但是在这种模式下创建的多线程并不能将多核利用起来,所有由这种模式下创建的线程最多只能共享一个CPU核,所以在有些场景下,需要将一个作业分配给一个独立的线程,并且每个独立的线程可以使用不同的CPU核资源,做到真正的并发执行。
如何实现呢?这里有两个办法
一.通过调用C函数库
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_thre