繁体   English   中英

Python线程循环

[英]Python Threading loop

我对这个THREDING示例有疑问。 我的工作相当不错,但是我的问题是在显示所有100个学生线程之后。 我试图让20名随机学生进入五个不同的班级,但是无论我做什么,我似乎都无法正常工作。 如果有人可以给我任何指导,我将不胜感激。

import random, time
from threading import Thread


class Students(Thread):
    ''' Represents a sleepy thread.'''


    def __init__(self, number, sleepMax):
        ''' Creates a thread with a given Name
        and a random sleep interval less than the maximum. '''
        Thread.__init__(self, name = "Student " + str(number))
        self._RequestInterval = random.randint(1, sleepMax)

    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''
        count = 1
        course = 1
        print(" %s, Awaiting Request: %d seconds" % \
              ( self.getName(), self._RequestInterval))
        time.sleep(self._RequestInterval)
        if count == 20:
            print("%s Has A Spot Obtained in Class" % self.getName(), + course)
            print("Class", course, "has reached it limit!")
            count += 1
            course =+ 1
        else:
            #print("Class ", course, " is full.")
            print("%s Has A Spot Obtained in Class" % self.getName(), + course)



def main():
    ''' Creates the user's number of threads with sleep
    interval less than the user's maximum. Then start
    the threads'''

    NumberOfStudents = 100
    RequestTimer = 5    
    threadList = []
    for count2 in range(NumberOfStudents):
        threadList.append(Students(count2 + 1, RequestTimer))
    for thread in threadList: thread.start()



main() 

我什至尝试在类外运行变量,但是崩溃了。

这有几个问题。

  1. countcourse变量仅在run功能中,因此它们仅在该功能中本地。 这意味着线程不共享此信息。 解决方案:将它们移到外面,使它们成为班级变量(也就是说,它们现在是Students.countStudents.course )。
  2. 您的打印语句有点混乱。 使用print(a,b,c,...)将在单独的一行上打印a,b,c,...中的每一个。 解决方案是,将线程的名称和课程号包含在一个元组中,然后稍微修改格式字符串。
  3. 如果曾经执行过if语句的那一部分(不是因为问题#1),则course =+ 1会将course设置为1 (因为它与course = +1相同)。 解决方案:翻转=+ ,使其为course += 1
  4. count += 1仅在count为20时发生。您需要在if语句的else部分中这样做。 同样,在然后的部分中,添加行count = 0以重置计数。
  5. 因为这些线程是异步运行的,所以在检查if count == 20之前, count确实会发生从19到21的情况。 解决此问题需要更高级的线程处理。

下面是解决所有这些问题的代码,除了最后一个(我将count == 20更改为count >= 20至少显示了一些有趣的事情)。

import random, time
from threading import Thread


class Students(Thread):
    ''' Represents a sleepy thread.'''
    count = 1
    course = 1

    def __init__(self, number, sleepMax):
        ''' Creates a thread with a given Name
        and a random sleep interval less than the maximum. '''
        Thread.__init__(self, name = "Student " + str(number))
        self._RequestInterval = random.randint(1, sleepMax)

    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''
        print(" %s, Awaiting Request: %d seconds" % \
              ( self.getName(), self._RequestInterval))
        time.sleep(self._RequestInterval)
        if Students.count >= 20:
            print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course))
            print("Class", Students.course, "has reached it limit!")
            Students.course += 1
            Students.count = 0
        else:
            #print("Class ", course, " is full.")
            print("%s Has A Spot Obtained in Class %s" % (self.getName(), Students.course))
            Students.count += 1



def main():
    ''' Creates the user's number of threads with sleep
    interval less than the user's maximum. Then start
    the threads'''

    NumberOfStudents = 100
    RequestTimer = 5    
    threadList = []
    for count2 in range(NumberOfStudents):
        threadList.append(Students(count2 + 1, RequestTimer))
    for thread in threadList: thread.start()



main() 
    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''
        count = 1
        course = 1

变量countcourse都是类的实例下,就像你能想到的有100个count变量,同样以course

如果尝试将两者移到类之外,则应添加一个gloabl引用,例如:

    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''

        global count, course

        count = 1
        course = 1

这可以防止崩溃,但也不能防止崩溃。 您可以想到,只有一个count和一个course ,但是您同时运行100个线程,也许它们都使用count=1 ,或者某些count=1某些count=2 ...

因此,我们需要将Mutex添加到公共变量(我们认为它是一种资源,需要设置互斥量以确保线程安全)。

编码:

import random, time, threading


count = 1
course = 1
mutex = threading.Lock()

class Students(threading.Thread):
    ''' Represents a sleepy thread.'''

    def __init__(self, number, sleepMax):
        ''' Creates a thread with a given Name
        and a random sleep interval less than the maximum. '''
        threading.Thread.__init__(self, name = "Student " + str(number))
        self._RequestInterval = random.randint(1, sleepMax)

    def run(self):
        '''Prints the thread's name and sleep interval and sleep
        for that interval. Print the name again at wake-up. '''

        global count, course

        print(" %s, Awaiting Request: %d seconds" % ( self.getName(), self._RequestInterval))
        time.sleep(self._RequestInterval)

        if mutex.acquire(1):

            print("%s Has A Spot Obtained in Class" % self.getName(), + course)

            if count == 20:
                count = 1
                course += 1
            else:
                count += 1

            mutex.release()


def main():
    ''' Creates the user's number of threads with sleep
    interval less than the user's maximum. Then start
    the threads'''

    NumberOfStudents = 100
    RequestTimer = 5
    threadList = []
    for count2 in range(NumberOfStudents):
        threadList.append(Students(count2 + 1, RequestTimer))
    for thread in threadList: thread.start()



main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM