Python 强制在特定CPU内核上执行线程
我有两个python线程,我想在CPU核心0上强制执行Thread1,在CPU核心1上强制执行Thread2。可能吗?如果是,怎么做?谢谢Python 强制在特定CPU内核上执行线程,python,multithreading,Python,Multithreading,我有两个python线程,我想在CPU核心0上强制执行Thread1,在CPU核心1上强制执行Thread2。可能吗?如果是,怎么做?谢谢 import threading import time #I would like to execute this thread on CPU core 0 class Thread1(threading.Thread): def __init__(self): self.running = 1; super
import threading
import time
#I would like to execute this thread on CPU core 0
class Thread1(threading.Thread):
def __init__(self):
self.running = 1;
super(Thread1, self).__init__()
def run(self):
while self.running:
print "Thread1"
#I would like to execute this thread on CPU core 1
class Thread2(threading.Thread):
def __init__(self):
self.running = 1;
super(Thread2, self).__init__()
def run(self):
while self.running:
print "Thread2"
if __name__ == "__main__":
thread1 = Thread1()
thread1.start()
thread2 = Thread2()
thread2.start()
start_time = time.time()
while (time.time() - start_time) <= 5:
print "main"
thread1.running = 0;
thread2.running = 0;
thread1.join()
thread2.join()
导入线程
导入时间
#我想在CPU核心0上执行此线程
类别Thread1(threading.Thread):
定义初始化(自):
自运行=1;
超级(Thread1,self)。\uuuu init\uuuu()
def运行(自):
自运行时:
打印“Thread1”
#我想在CPU核心1上执行这个线程
螺纹2类(螺纹.螺纹):
定义初始化(自):
自运行=1;
超级(Thread2,self)。\uuuu init\uuuu()
def运行(自):
自运行时:
打印“Thread2”
如果名称=“\uuuuu main\uuuuuuuu”:
thread1=thread1()
thread1.start()
thread2=thread2()
thread2.start()
开始时间=time.time()
虽然(time.time()-start_time),请看一下sched_setaffinity()
,但请注意,它适用于进程,而不是线程。首先,我不认为手动执行该操作有什么好处(而是允许操作系统决定)。第二:由于GIL的原因,除非您使用的是其他Python解释器,而不是CPython,否则这并不重要。我需要手动执行此操作,因为应用程序的目的是在特定的内核上生成固定数量的CPU负载(这是一个压力测试),请看一下,这样您就不必自己编写代码了