当前位置: 代码迷 >> PB >> pb 8.0.3 注销线程就程序崩溃解决方法
  详细解决方案

pb 8.0.3 注销线程就程序崩溃解决方法

热度:41   发布时间:2016-04-29 07:32:27.0
pb 8.0.3 注销线程就程序崩溃
本帖最后由 jeremyruan 于 2012-10-25 12:03:16 编辑
最近使用pb 8.0.3 开发一程序需要串口通信,串口通讯代码就是从csdn下载的源码
1、首先定义一个线程对象uo_thread用于后台循环判断缓冲。每50ms读一次缓冲,有数据接收就接收,有发送就发送
of_start()
do while true
inv_arg.triggerevent("ue_thread")
sleep(50)//此函数是api函数(Subroutine Sleep (ulong dwMilliseconds) Library "Kernel32.DLL"),非pb  自带的sleep
loop

2、定义一个uo_pbcomm对象,在该对象的constructor中实例化线程uo_thread

if isvalid(uo_thread_pbcomm) then destroy uo_thread_pbcomm
uo_thread_pbcomm = create uo_thread
SharedObjectRegister("uo_thread","pbcommobject") //将uo—thread对象注册为pbcommobject
SharedObjectGet("pbcommobject",uo_thread_pbcomm) //用uo—thread引用共享对象uo_thread_pbcomm 
uo_thread_pbcomm.of_setparent(this) //用中间对象给uo—thread中的实例变量赋值 
uo_thread_pbcomm.Post of_start() //利用服务器推送技术,异步调用共享对象中的uf—start() 

然后我该对象的destructor 函数中 销毁改该线程对象并释放内存
if isvalid(uo_thread_pbcomm) then
  SharedObjectUnRegister("pbcommobject") 
  destroy uo_thread_pbcomm
end if

奇怪的是只要运行到 destroy uo_thread_pbcomm 程序必崩溃。由于该模块写在一个子窗口中,如果不运行destroy uo_thread_pbcomm释放内存,则关闭子窗口,则直接退出整个程序,并在程序退出后报错!

请大家帮忙看看





------解决方案--------------------
if isvalid(uo_thread_pbcomm) then destroy uo_thread_pbcomm
// uo_thread_pbcomm = create uo_thread //这句可以不要SharedObjectRegister("uo_thread","pbcommobject") //将uo—thread对象注册为pbcommobject
SharedObjectGet("pbcommobject",uo_thread_pbcomm) //用uo—thread引用共享对象uo_thread_pbcomm  
uo_thread_pbcomm.of_setparent(this) //用中间对象给uo—thread中的实例变量赋值  
uo_thread_pbcomm.Post of_start() //利用服务器推送技术,异步调用共享对象中的uf—start()  

//////////////////////////////////
of_start()
do while b_start
yield() //这里加 yield()inv_arg.triggerevent("ue_thread")
sleep(50)//此函数是api函数(Subroutine Sleep (ulong dwMilliseconds) Library "Kernel32.DLL"),非pb 自带的sleep
loop


------解决方案--------------------
引用:
可能么?线程不能共享全局变量。
of_start()
do while b_start
yield() //这里加 yield()inv_arg.triggerevent("ue_thread")
sleep(50)//此函数是api函数(Subroutine Sleep (ulong dwMilliseconds) Library "Kernel32.DLL"),非pb 自带的slee……

在PB中全局变量确实不能互访,起码PB12+是这样的,这个我一开始以为是个BUG,后来发现可能真的是个BUG。。。
至于如何给主线程发送通知信号,其实可以用事件通知来做,在我的BLOG里有写,这里给一个简单的模型:

nvo_CallBack:
    (none) Event ue_ThraedStart()
    {
        ib_Started=True
    }
    (none) Event ue_ThraedStop()
    {
        ib_Started=False
    }
uo_thread of_Start():
    in_CallBack.Event ue_ThreadStart()
    do while true
        yield()
        if Not b_Start then exit
        sleep(50)
    loop
    in_CallBack.Event ue_ThreadStop()

uo_pbcomm Destructor Event:
    if IsValid(uo_thread_pbcomm) then
  相关解决方案