线程以串行方式运行

时间:2014-02-22 04:49:56

标签: python multithreading

我正在尝试为我实验室的实验设计视觉刺激。当用户按下键时,刺激应该停止。整个实验都是时间敏感的,所以我不能连续运行密钥检查。

我写的代码看起来像这样。


class designStim:
    '''
    This is class to hold functions designing the stimulus. There
    are other functions in this class but the only one that is
    called is the following.
    '''
    def deisgnStart(self)
        #This function returns a dictionary variable containing
        #the raw stimulus

class dispStim(threading.Thread):
    def __init__(self,stimdata,q):
        threading.Thread.__init__(self)

    #*Assign the other data from stimdata to self*
    def run(self):
        #Code to run the stimulus

class checkKbdAbort(threading.Thread):
    def __init__(self,q):
        threading.Thread.__init__(self)

    def run(self):
        #Code to check for keyboard key press. In case of key press,
        #use the queue to abort     dispStim*


if __name__ == '__main__':
    a=designStim('test')
    stimdata=a.designStart()
    q=Queue()
    thread1=dispStim(stimdata,q)
    thread2=checkKbdAbort(q)
    thread1.start()
    thread2.start()

这个代码在我连续运行时起作用,这使我相信我的显示脚本是正确的。但是,当我以这种形式运行代码时,两个线程不会并行运行。 thread1执行,然后thread2运行。在thread1运行期间,刺激不会显示。在类初始化/调用期间我是否犯了错误?

3 个答案:

答案 0 :(得分:0)

虽然我无法肯定地回答你的问题(因为我没有看到一个完整的例子,因此不知道为什么事情似乎是连续执行的),并且放弃了复制到你的问题中的代码中的拼写错误,你试图做的似乎基本正确。如果您继承threading.Thread并提供run()定义,并且如果通过start()启动每个线程实例,则线程应并行运行。 (线程1 可能获得一个小的开头,因为它首先从父线程开始,但我猜这在这种情况下无关紧要。)

这是一个工作示例,显示了线程应该并行工作的位置:

import sys
import threading

# Using sys.stdout.write() instead of print; it seems nicer for
# demoing threads in CPython :)

class Fizz(threading.Thread):
    def run(self):
        for i in xrange(10):
            sys.stdout.write("fizz\n")

class Buzz(threading.Thread):
    def run(self):
        for i in xrange(10):
            sys.stdout.write("buzz\n")

fizz = Fizz()
buzz = Buzz()
fizz.start()
buzz.start()

以下是我的输出结果:

C:\Users\Vultaire>test.py
fizz
fizz
fizz
fizz
fizz
buzz
buzz
buzz
buzz
fizz
buzz
fizz
fizz
buzz
fizz
fizz
buzz
buzz
buzz
buzz

示例中的线程似乎是以这种方式启动的,因此它们应该并行运行。我猜这个问题在别的地方?或者线程并行运行并且看起来不像? (如果您需要进一步的帮助,请提供更完整的代码示例!:))

答案 1 :(得分:0)

Python中的多线程实现起来有点棘手。你应该看看这个。

Look at this

What is a global interpreter lock (GIL)?

PYTHON THREADS AND THE GLOBAL INTERPRETER LOCK

答案 2 :(得分:0)

From this,也许它是并行工作但是第二个线程启动然后第一个线程终止的时间。您可以尝试在函数中添加休眠时间,以模拟IO的缓慢程度,如本示例所示

import threading
from time import sleep

def something():
    for i in xrange(10):
        sleep(0.01)
        print "Hello"

def my_thing():
    for i in xrange(10):
        sleep(0.01)
        print "world"   

threading.Thread(target=something).start()
threading.Thread(target=my_thing).start()