Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从函数中调用信号量绑定线程将导致`NameError:name';sema';没有定义`_Python_Multithreading_Semaphore - Fatal编程技术网

Python 从函数中调用信号量绑定线程将导致`NameError:name';sema';没有定义`

Python 从函数中调用信号量绑定线程将导致`NameError:name';sema';没有定义`,python,multithreading,semaphore,Python,Multithreading,Semaphore,如果我想限制要创建的线程数量,我将使用下面示例中的信号量 def TestFunction( m, n ): sema.acquire() print(m+n) sema.release() maxthreads = 2 sema = threading.Semaphore(value=maxthreads) j=6 for i in range(0, 2*2): #totalNumberOfRows thread = threading.Thread(tar

如果我想限制要创建的线程数量,我将使用下面示例中的信号量

def TestFunction( m, n ):
    sema.acquire()
    print(m+n)
    sema.release()

maxthreads = 2
sema = threading.Semaphore(value=maxthreads)
j=6

for i in range(0, 2*2): #totalNumberOfRows
    thread = threading.Thread(target=TestFunction,args=( i , j ))
    thread.start()
但是,如果我从函数调用线程,我会遇到一个
namererror:name'sema'未定义
错误

def TestFunction( m, n ):
    sema.acquire()
    print(m+n)
    sema.release()

def CallThreads(k):

    maxthreads = 2
    sema = threading.Semaphore(value=maxthreads)
    j=6

    for i in range(0, k*2): #totalNumberOfRows
        thread = threading.Thread(target=TestFunction,args=( i , j ))
        thread.start()

for mstr in range(0, 10): 
    CallThreads(mstr)
在这种情况下,我应该在两个函数之外定义
sema
?如果是这样,在
CallThreads
中创建的
线程能否识别此
sema
并在
TestFunction
中使用它

可能的解决办法:

def TestFunction( m, n ):
    sema.acquire()
    print(m+n)
    sema.release()

def CallThreads(k):

    maxthreads = 2
    j=6

    for i in range(0, k*2): #totalNumberOfRows
        thread = threading.Thread(target=TestFunction,args=( i , j ))
        thread.start()

for mstr in range(0, 10): 
    sema = threading.Semaphore(value=maxthreads)
    CallThreads(mstr)

函数中定义的变量是此函数的局部变量,因此需要函数外部的全局变量。顺便说一下:您不限制创建的线程数,只限制更多线程等待时运行的线程数(并在执行此操作时使用系统资源).函数中定义的变量是此函数的局部变量,因此需要函数外部的全局变量。顺便说一下:您不限制创建的线程数,只限制更多线程等待时运行的线程数(并在执行此操作时使用系统资源)。