Python _thread让每个线程按顺序处理相应的数字

时间:2013-10-20 19:56:18

标签: python multithreading python-3.x python-multithreading

我希望第一个线程处理第一个,第五个和第九个,第二个将获得第二个 - 第六个 - 第十个,第三个 - 第七个,第十一个,第四个将是第八个和第十二个。我知道它是(4 * counter + original)的重复模式,但是在移动实际的_thread进程时我迷失了。这是我到目前为止所拥有的。 如果我说错了,就告诉我,因为我愿意接受建议。

编辑 - 我正在使用Python 3.3

def calc(threadName):
    testRange = 100
    testNumber = 100
    timesToTest = 25
    testCounter = 0
    if threadName  == 'ThreadOne':
        testNumber = (testNumber)   + 5*(testCounter)
    if threadName == 'ThreadTwo':
        testNumber = (testNumber+1) + 5*(testCounter)
    if threadName == 'ThreadThree':
        testNumber = (testNumber+2) + 5*(testCounter)
    if threadName == 'ThreadFour':
        testNumber = (testNumber+3) + 5*(testCounter)

    while testCounter < timesToTest:
        testCounter +=1
        while testRange >= 0:
            answer = ((testNumber*3) - ((testNumber-1)**2))
            testbool = isprime(answer)
            print('Testing '+str(testNumber)+' on '+str(threadName))
            testNumber +=1
            testRange -= 1
            if testbool:
                list.append((threadName,testNumber,answer))


threadOne = _thread.start_new_thread(calc,('ThreadOne', ))
threadTwo = _thread.start_new_thread(calc,('ThreadTwo', ))
threadThree = _thread.start_new_thread(calc,('ThreadThree', ))
threadFour = _thread.start_new_thread(calc,('ThreadFour', ))

while 1:
    pass

尝试了这个:

import threading
import queue

class Worker(threading.Thread):
    global results_list
    print('in main class')
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.jobs_queue = queue.Queue()
        self.results_list = list()
        print('in init')

    def isprime(self,n):
        n = abs(int(n))
        print('in isprime')
        if n < 2:
            return False
        if n == 2:
            return True

        if not n & 1:
            return False

        for x in range(3, int(n**0.5)+1, 2):
            if n % x == 0:
                return False
        return True

    def run(self):
        print('in run')
        while True:
            testNumber = self.jobs_queue.get()
            if testNumber == "END":
                return
                # here, do your stuff with 'testNumber'
            # for example, let's multiply it by 2
            answer = ((testNumber**3) - ((testNumber-1)**3))
            testbool = self.isprime(answer)
            if testbool:# results are appended to a list
                self.results_list.append((self.name,testNumber,answer))
    def calc(self, n):
        print('in calc')
        self.jobs_queue.put(n)
        if not self.is_alive():
            self.start()
    def get_result(self):
        print('in get_result')
        return self.results_list
    def stop(self):
        print('in stop')
        # tell the thread to stop,
        # once jobs in queue are done
        self.jobs_queue.put("END")
        self.join()
print('Anything')
workers = [Worker('thread 1'), Worker('thread 2'), Worker('thread 3'), Worker('thread 4')]

for n in range(100):
    print('here 1')
    w = workers[n % 4]
    w.calc(n)

for w in workers:
    w.stop()

for w in workers:
    x=1
    # print(results_list)

1 个答案:

答案 0 :(得分:1)

据我所知,你想要一个由4个工作线程组成的池,公平排队同样的“工作” 在这4个线程之间。

我会做更多类似的事情:

import threading
import queue

class Worker(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.jobs_queue = queue.Queue()
        self.results_list = list()
    def run(self):
        while True:
            testNumber = self.jobs_queue.get()
            if testNumber == "END":
                return
            # here, do your stuff with 'testNumber'
            # for example, let's multiply it by 2
            answer = testNumber * 2
            # results are appended to a list
            self.results_list.append((self.name,testNumber,answer))
    def calc(self, n):
        self.jobs_queue.put(n)
        if not self.is_alive():
            self.start()
    def get_result(self):
        return self.results_list
    def stop(self):
        # tell the thread to stop,
        # once jobs in queue are done
        self.jobs_queue.put("END")
        self.join()

workers = [Worker('thread 1'), Worker('thread 2'), Worker('thread 3'), Worker('thread 4')]

for n in range(100):
    w = workers[n % 4]
    w.calc(n)

for w in workers:
    w.stop()

for w in workers:
    print(w.get_result())