我有一个16核的机器,但我目前的调整大小功能只使用一个核心,这对于大型图像目录来说效率非常低.
def generateThumbnail(self, width, height):
"""
Generates thumbnails for an image
"""
im = Image.open(self._file)
(detected_width,detected_height) = im.size
#Get cropped box area
bbox = self.getCropArea(detected_width, detected_height, width, height)
#Crop to box area
cropped_image = im.crop(bbox)
#Resize to thumbnail
cropped_image.thumbnail((width, height), Image.ANTIALIAS)
#Save image
cropped_image.save(self._path + str(width) + 'x' +
str(height) + '-' + self._filename, "JPEG")
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.谢谢.
我有一个事件驱动的聊天机器人,我正在尝试实施垃圾邮件防护.我想让一段时间内表现不佳的用户沉默,而不会阻塞应用程序的其余部分.
这是不起作用的:
if user_behaving_badly():
ban( user )
time.sleep( penalty_duration ) # Bad! Blocks the entire application!
unban( user )
Run Code Online (Sandbox Code Playgroud)
理想情况下,如果user_behaving_badly()为true,我想启动一个新的线程,除了禁止用户之外什么都不做,然后睡一会儿,解开用户,然后线程消失.
根据这个,我可以使用以下内容完成我的目标:
if user_behaving_badly():
thread.start_new_thread( banSleepUnban, ( user, penalty ) )
Run Code Online (Sandbox Code Playgroud)
"简单"通常是"好"的指标,这很简单,但我听到的关于线程的一切都说他们会以意想不到的方式咬你.我的问题是:有没有比这更好的方法来运行一个简单的延迟循环而不阻塞应用程序的其余部分?
AFAIK,threading.Thread实例实际上不能并行运行,因为Global Interpreter Lock会强制一个线程只能在任何时间运行(除了阻塞I/O操作时).
ParalellPython使用该threading模块.
但是,如果我向它提交多个本地作业,它会并行执行它们,或者至少看起来如此.我有8个核心,如果我开始8个作业来简单地运行空循环,它们都占用CPU的12-13%(这意味着它们每个都在一个核心上执行,我可以在我的任务管理器中看到这个)
有谁知道这会怎么样?
我使用以下代码来处理SIGINT事件。该代码将multiprocessing.event设置为“唤醒”正在等待的主线程。
import multiprocessing
import signal
class Class1(object):
_stop_event = multiprocessing.Event()
@staticmethod
def interrupt():
Class1._stop_event.set()
def wait(self):
print("Waiting for _stop_event")
if Class1._stop_event.wait(5):
print("_stop_event set.")
else:
print("Timed out.")
def stop(signum, frame):
print("Received SIG")
Class1.interrupt()
signal.signal(signal.SIGINT, stop)
c = Class1()
c.wait()
Run Code Online (Sandbox Code Playgroud)
没有任何信号,wait方法将在10秒后超时,并且该过程将按预期方式退出,并显示以下输出:
Waiting for _stop_event
Timed out.
Run Code Online (Sandbox Code Playgroud)
发送SIGINT信号时,将处理该信号,但event.wait方法不会立即或在超时后都不会返回。该过程永远不会退出。输出为:
Waiting for _stop_event
^CReceived SIG
Run Code Online (Sandbox Code Playgroud)
我可以继续发送SIGINT。该过程将不会退出,输出为:
Waiting for _stop_event
^CReceived SIG
^CReceived SIG
^CReceived SIG
^CReceived SIG
....
Run Code Online (Sandbox Code Playgroud)
如果将Class1.wait方法替换为event.is_set检查,一切都会按预期进行:
def wait(self):
print("Waiting for _stop_event")
while True:
if Class1._stop_event.is_set():
print("_stop_event set.")
break
Run Code Online (Sandbox Code Playgroud)
该过程退出,输出为:
Waiting …Run Code Online (Sandbox Code Playgroud) 如果d是字典,那么显然CPython不喜欢它,如果另一个线程修改d
[k for k in d]
Run Code Online (Sandbox Code Playgroud)
被评估.如何使用
list(d)
Run Code Online (Sandbox Code Playgroud)
代替?这是线程安全的吗?
我在python中遇到线程问题,问题似乎是当我调用线程时,随后调用raw_input()会阻塞线程。这是最小的例子
import threading
import time
class tread_test(threading.Thread):
def __init__(self):
self.running = True
threading.Thread.__init__(self)
#
def run(self):
self.foo()
#
def foo(self):
print "Spam, Spam, Spam"
self.task = threading.Timer(0.5, self.foo)
self.task.start()
#
def stop(self):
self.running = False
self.task.cancel()
#
#
if __name__ == "__main__":
a = tread_test()
print "Starting now"
a.start()
raw_input()
a.stop()
print "Stopping now"
Run Code Online (Sandbox Code Playgroud)
我对此的期望是:
Starting now
Spam, Spam, Spam
Spam, Spam, Spam
Spam, Spam, Spam
** user hits enter **
Stopping now
Run Code Online (Sandbox Code Playgroud)
这就是给我的:
>>>
Starting now
Spam, Spam, Spam …Run Code Online (Sandbox Code Playgroud) 我一直在查看龙卷风文件.
在阅读IOLoop时,有下面的内容.
通常,在构造异步对象时应使用IOLoop.current作为缺省值,并在使用IOLoop.instance时使用IOLoop.instance来表示从另一个主线程进行通信.
有意义的是,我必须使用instance()方法通过共享一个全局IOLoop实例的多线程进行通信.
但是,什么是asynchronous object在这里,我为什么要使用current()中的情况下,asynchronous object?
Lock.acquire/release在以下声明中是否有一个隐藏的内容:
my_thread_local = threading.local()
my_thread_local.some_value = 1
Run Code Online (Sandbox Code Playgroud)
这个怎么样:
local_variable = my_thread_local.some_value
Run Code Online (Sandbox Code Playgroud) 我可以用来KafkaConsumer在单独的线程中使用消息。
但是,当我使用multiprocessing.Process而不是时threading.Thread,出现错误:
OSError: [Errno 9] Bad file descriptor
该问题和文档表明使用多处理并行使用消息是可能的。有人可以分享一个有效的例子吗?
编辑
这是一些示例代码。抱歉,原始代码太复杂了,因此我在这里创建了一个示例,希望可以传达正在发生的事情。如果我使用threading.Thread而不是,此代码可以正常工作multiprocessing.Process。
from multiprocessing import Process
class KafkaWrapper():
def __init__(self):
self.consumer = KafkaConsumer(bootstrap_servers='my.server.com')
def consume(self, topic):
self.consumer.subscribe(topic)
for message in self.consumer:
print(message.value)
class ServiceInterface():
def __init__(self):
self.kafka_wrapper = KafkaWrapper()
def start(self, topic):
self.kafka_wrapper.consume(topic)
class ServiceA(ServiceInterface):
pass
class ServiceB(ServiceInterface):
pass
def main():
serviceA = ServiceA()
serviceB = ServiceB()
jobs=[]
# The code works fine if I used threading.Thread …Run Code Online (Sandbox Code Playgroud) python python-multithreading apache-kafka python-multiprocessing
我尝试利用python的池多处理功能。
与我如何设置块大小无关(在Windows 7和Ubuntu下-后者在下面具有4个内核),并行线程的数量似乎保持不变。
from multiprocessing import Pool
from multiprocessing import cpu_count
import multiprocessing
import time
def f(x):
print("ready to sleep", x, multiprocessing.current_process())
time.sleep(20)
print("slept with:", x, multiprocessing.current_process())
if __name__ == '__main__':
processes = cpu_count()
print('-' * 20)
print('Utilizing %d cores' % processes)
print('-' * 20)
pool = Pool(processes)
myList = []
runner = 0
while runner < 40:
myList.append(runner)
runner += 1
print("len(myList):", len(myList))
# chunksize = int(len(myList) / processes)
# chunksize = processes
chunksize = 1
print("chunksize:", chunksize)
pool.map(f, …Run Code Online (Sandbox Code Playgroud) python multithreading multiprocessing python-multithreading python-multiprocessing