用于python的多线程像素绘图库

时间:2014-03-01 11:08:42

标签: multithreading python-2.7 pygame pixel

我正在做一个图形项目,只能使用像素绘图功能。我遇到了pygame,但它似乎没有提供它在线程中使用的调用。请建议我解决这个或任何其他可以与线程一起使用的python库。

#! /usr/bin/env python
import threading
import time

    class plotterthread(threading.Thread):
    def __init__(self,screen,queue):
        threading.Thread.__init__(self)
        self.screen = screen
        self.__queue__ = queue
        self._colorset = False
        self.kill = False

    def setcolor(self,r,g,b):
        self._r = r
        self._g = g
        self._b = b
        self._colorset = True

    def run(self):
        try:
            while not self.__queue__.empty() and not self.kill:
                (x,y) = self.__queue__.get(timeout=1)
                if not self._colorset:
                                    #this is where error occures
                                    #this calls pygame.set_at() method
                    self.screen.plotpixel((x,y))

                else:
                    self.screen.plotpixel((x,y),(self._r,self._g,self._b))
        except:
            pass


class plotter:
    def __init__(self,screen,min,max,queue,ppt=50):
        self.screen = screen
        self.min = min
        self.max = max
        self.ppt = ppt # pixels per thread
        self.coords = queue



    def plot(self):
        noOfcoords = self.coords.qsize()
        noOfthreads = int(noOfcoords/self.ppt)
        if noOfthreads > self.max:
            noOfthreads = self.max
        elif noOfthreads < self.min:
            noOfthreads = self.min

        self.threadpool = []
        for i in range(noOfthreads):
            pthread = plotterthread(screen = self.screen,queue = self.coords)
            self.threadpool.append(pthread)
            pthread.start()


        while True:
            try:
                livethreads = 0
                for t in self.threadpool:
                    if t is not None and t.isAlive():
                        livethreads += 1
                        t.join(timeout=1)
                if livethreads == 0:
                    break
            except KeyboardInterrupt:
                for threads in self.threadpool:
                    if threads is not None and threads.isAlive():
                        threads.kill = True
                break

这里,screen是我试图绘制的窗口的实例。 queue是队列,其中包含要绘制的所有计算坐标。

我想要做的就是首先计算所有像素并将它们推入队列然后与线程共享队列以并行绘制它们以加速该过程。

0 个答案:

没有答案