如何在pyobj中生成线程

2024-09-20 23:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何使用pyobjc进行一些基本的原型设计。现在我有了一个主UI设置和一个运行主应用程序的python脚本。唯一的问题是当脚本运行时,脚本在主线程上运行,从而阻塞了UI。在

这是我在python中尝试使用线程导入的示例代码片段:

def someFunc(self):
    i = 0
    while i < 20:
        NSLog(u"Hello I am in someFunc")
        i = i + 1

@objc.IBAction
def buttonPress(self, sender):
    thread = threading.Thread(target=self.threadedFunc)
    thread.start()

def threadedFunc(self):
    NSLog(u"Entered threadedFunc")
    self.t = NSTimer.NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1/150., self,self.someFunc,None, True)
    NSLog(u"Kicked off Runloop")
    NSRunLoop.currentRunLoop().addTimer_forMode_(self.t,NSDefaultRunLoopMode)

单击按钮时,threadedFunc中的NSLogs将输出到控制台,但它从不输入someFunc

所以我决定用nshread启动一个线程。在苹果的文档中,Objective-C调用如下所示:

^{pr2}$

因此,我将其转换为pyobjc规则,用于调用objective-c函数:

detachNewThreadSelector_aSelector_aTarget_anArgument_(self.threadedFunc, self, 1)

因此,在上下文中,IBAction函数如下所示:

@objc.IBAction
def buttonPress(self, sender):
    detachNewThreadSelector_aSelector_aTarget_anArgument_(self.threadedFunc, self, 1)

但是当按钮被按下时,我得到一条消息:全局名“detachNewThreadSelector”没有定义。在

我也尝试过使用grandcentraldispatch进行类似的尝试,但是相同的消息不断出现,即global namesome_grand_central_function没有被定义

很明显,我不理解python线程的细微差别,或者pyobjc调用约定,我想知道是否有人能对如何继续进行有所帮助。在


Tags: self脚本uidefpyobjc线程threadsender
2条回答

翻译后的函数名应为

detachNewThreadSelector_toTarget_withObject_(aSelector, aTarget, anArgument)

您当前正在将转换规则应用于arguments部分,而不是Objective-C调用部分。使用示例中的参数调用函数:

^{pr2}$

所以我得到了我想要的结果,按照下面的结构。就像我在回复评论时所说的:对于后台线程,nshread将不允许您执行某些任务。(即更新某些UI元素、打印等)。所以我使用performSelectorOnMainThread_withObject_waitUntilDone_来处理线程操作之间需要执行的操作。手术时间短,强度不高,对性能影响不大。谢谢你米切尔·考瓦·特乔给我指出了正确的方向!在

def someFunc(self):
    i = 0
    someSelector = objc.selector(self.someSelector, signature='v@:')
    while i < 20:
        self.performSelectorOnMainThread_withObject_waitUntilDone(someSelector, None, False)
        NSLog(u"Hello I am in someFunc")
        i = i + 1

@objc.IBAction
def buttonPress(self, sender):
    NSThread.detachNewThreadSelector_toTarget_withObject_(self.threadedFunc, self, 1)

def threadedFunc(self):
    NSLog(u"Entered threadedFunc")
    self.t = NSTimer.NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1/150., self,self.someFunc,None, True)
    NSLog(u"Kicked off Runloop")
    self.t.fire()

相关问题 更多 >

    热门问题