Running a method from an object in another Thread
Asked Answered
E

1

2

I have LibGDX Application in which I paint and a Thread for Client or Server. Connections are done using Kryonet. When your opponent creates does something a message is recieved linke so:

public void received(Connection con, Object object) {

                            TroopMessage tm = (TroopMessage)object;                         
                            fortress.map.addSoldier(tm.kind, true);
                            System.out.println("recieved");

                            connection = con;
}

When this callback is called (and it is correctly) I get "No OpenGL context found in the current thread". I think it is looking for the object fortress within the MyClient Thread. I want to call to fortress.map.addSoldier which refers to an object currently existing in another thread.

public class Fortress extends Game implements ApplicationListener{
    private OrthographicCamera camera;
    private SpriteBatch batcher;

    public static MyServer server;
    public static MyClient client;

    public static Map map;
[....]

How can I call the method in from another thread?

thanks in advance

Extradition answered 26/5, 2013 at 13:24 Comment(3)
An Object does not belong to or exist in a specific thread, so that is not the problem here.Dessiedessma
Have you tried searching? #14347840Innoxious
Yes I have seen that SO but they talk about "So you can only access this context from the same thread". How can I do that?Extradition
P
4

In Libgdx you can use Gdx.app.postRunnable(Runnable r) to ask the main OpenGL-context-having render thread to run some code. See the Libgdx wiki about application threading here: https://code.google.com/p/libgdx/wiki/ApplicationThreading

As the comments point out, generally Java objects are not "owned" by a thread. The "OpenGL context" is something of an exception to this, as only one thread is allowed to make changes to the OpenGL state.

Proparoxytone answered 26/5, 2013 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.