UE4子线程调用游戏主线程注意事项 (含队列问题)

Non-GameTthread调用GameThread。

——————————————————

案例:

游戏起一个socket客户端与外部socket 服务器保持长连接通信;开辟一个接受线程(via. FRunnableThread::Create)来接受socket服务器的消息,然后在接受消息处理中有涉及到调用GameInstance或GameMode中的方法,导致程序宕掉(自个写的一个简单demo上又都正常,猜测可能是所调用方法的具体实现不同导致的)。

后面用IsInGameThread()判断,在处理函数中触发回调时间的时候,是出于非GameThread的,问题可能在于此?

然后google了下,比较有参考价值的如下两条:

1.How do I execute code on the Game thread from an FRunnable thread?

https://answers.unrealengine.com/questions/262585/how-do-i-execute-code-on-the-game-thread-from-an-f.html

2.[UE4]如何跨线程访问GameThread中的数据

https://blog.csdn.net/wag2765/article/details/84796693

https://aigo.iteye.com/blog/2296553

大致的方法都是在主线程创建一个队列(eg.static TQueue<FString> To_be_synchronized_object; ),然后子线程收到socket消息时,往主线程的队列里塞,然后主线程在tick中去取队列消息,进行处理。

 

符些参考的链接,含队列:

https://wiki.unrealengine.com/Multi-Threading:_How_to_Create_Threads_in_UE4#What_Not_to_Do

https://zhuanlan.zhihu.com/p/38881269

https://answers.unrealengine.com/questions/702658/when-i-use-tqueuegot-a-compiler-error.html

https://www.reddit.com/r/unrealengine/comments/6ll3ty/tqueue_initialization/

 

====================================================================================

//AsyncTask (ENamedThreads::GameThread ,[](){
        //    //此处在游戏线程上执行的代码
        //});

待研究。。。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Python 中,线程调用线程的方法可以使用 Queue 模块来实现。具体步骤如下: 1. 在线程中创建一个 Queue 对象,并将需要调用的方法和参数封装成一个元组,放入队列中。 2. 在线程中,通过 Queue.get() 方法获取队列中的元组,其中包需要调用的方法和参数。 3. 线程通过调用该方法,并将参数传递给方法。 4. 如果需要在线程中获得该方法的返回值,可以将返回值封装成一个元组,放入另一个队列中。 5. 在线程中,通过 Queue.get() 方法获取线程中的返回值元组,其中包方法的返回值。 下面是一个简单的示例代码: ```python import threading import queue def main_thread_method(arg): print(f"Main thread method called with arg {arg}") def worker_thread(queue): while True: # 阻塞等待线程传来的任务 task = queue.get() method, args = task # 调用方法,并将返回值封装成元组返回给线程 ret = method(*args) queue.put(ret) if __name__ == "__main__": # 启动线程 q = queue.Queue() t = threading.Thread(target=worker_thread, args=(q,)) t.start() # 在线程中将任务加入队列 q.put((main_thread_method, ("hello",))) # 等待线程返回结果 ret = q.get() print(f"Received result from worker thread: {ret}") ``` 在此示例中,线程调用 main_thread_method 方法,并将参数 "hello" 封装成一个任务元组加入队列中。线程队列中获取任务,并执行该方法,将返回值封装成元组后再次放入队列中。线程队列中获取返回值元组,其中包方法的返回值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值