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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python _thread让每个线程按顺序处理相应的数字相关的知识,希望对你有一定的参考价值。

我希望第一个线程处理第一个,第五个和第九个,第二个将获得第二个 - 第六个 - 第十个,第三个 - 第七个,第十一个,第四个将是第八个和第十二个。我知道它是(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)
答案

据我所知,你想要一个由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())

以上是关于Python _thread让每个线程按顺序处理相应的数字的主要内容,如果未能解决你的问题,请参考以下文章

有三个线程,怎么让他们按顺序执行?

MFC中如何让多线程按先后顺序执行,第一个来的先执行,以后按先后到达的顺序执行

Python 将任务排入队列并按顺序获取结果

如何保证线程按顺序执行

如何让多个线程顺序执行

python