gpt4 book ai didi

Java 同步问题 - 主线程被协程实现锁定

转载 作者:行者123 更新时间:2023-11-30 12:06:21 25 4
gpt4 key购买 nike

我正在开发一款游戏,但我遇到了线程同步问题。我很遗憾地没有正确地写这个,所以主线程不会因此而挂起。短篇故事它在我的主游戏线程(游戏循环)中创建了一个锁。我会尽我所能提供详细信息。问题与游戏框架无关,因为这是我锁定所有内容的通用代码。

背景:

游戏中发生的 Action 作为协程执行。由于 Java 中没有协程功能,因此它们已通过使用线程实现为协程。想法是有可中断的 Action ,所以当新的 Action 开始时,当前的执行被暂停,直到新的 Action 完成。这种行为也可以有更多的深度。

问题:

在这种情况下如何正确地进行同步,或者如何正确地保护我的主线程循环(示例中给出的更新方法)使其不挂起?

这是简化的用例。执行的每个操作,即移动单元,升级任何已完成的作为协程或协程集执行的内容。

Game init:
Player turn: move units around, upgrade stuff and so on
Ai turn:
Calculate stuff
Calculate more stuff
Evaluate player strength
Evaluate choke points
More calculations
Plan attack actions
Move units>
Create action (Coroutines) for every single move >
Coroutine executing for move
We have to fight in battle between two units
Create action (Coroutines) for every Combat
Coroutines executing for Combat
Coroutine for combat finished
Coroutine for move finished
repeat few times, sometime with and without battle
Move Coroutine finished
Move loop finished
Do more stuff
End ai turn;

我一直在查看线程转储以找出导致此问题的原因,以及它的恢复方法。

可以看到锁的线程转储:

主线程已锁定:


"LWJGL Application" #18 prio=5 os_prio=0 tid=0x0000000020062800 nid=0x3b20 in Object.wait() [0x0000000022a7f000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at package_name.Coroutine$CoroutineExecutor.resume(Coroutine.java:319)
- locked <0x00000006c3aeddd8> (a java.lang.Thread)
at package_name.Coroutine.resume(Coroutine.java:409)
at package_name.screens.GameScreen.render(GameScreen.java:430)
at com.badlogic.gdx.Game.render(Game.java:46)
at package_name.Game.render(Game.java:273)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:223)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)

Locked ownable synchronizers:
- None

其他线程锁定了主线程:

"Thread-6" #32 prio=5 os_prio=0 tid=0x0000000020a9e000 nid=0xc94 runnable [0x000000014d64e000]
java.lang.Thread.State: RUNNABLE
//Doing something here which might take a second or two
at package_name.Coroutine$CoroutineExecutor$1.run(Coroutine.java:242)
- locked <0x00000006c3aeddd8> (a java.lang.Thread)
at java.lang.Thread.run(Thread.java:748)

Locked ownable synchronizers:
- None

完整协程代码:

package com.game.coroutine;

import com.game.coroutine.CoroutineDeath;
import com.game.coroutine.DeadCoroutineException;
import com.game.coroutine.InternalCoroutineException;
import com.game.coroutine.ResumeSelfCoroutineException;
import com.game.coroutine.YieldOutsideOfCoroutineException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
* An implementation of Lua-like coroutines.
* Supports returning values with yield, nesting and it might be thread safe.
*/
public class Coroutine {
private static final Logger log = LoggerFactory.getLogger(Coroutine.class);
private static List<CoroutineExecutor> executorPool = new ArrayList<>();

private final Runnable runnable;
private Object returnValue;
private boolean finished;

/** I think CoroutineExecutor is used to map Lua coroutines (not present in Java) to Java Threads.
*
* */
private static class CoroutineExecutor {

private boolean running = true;
private final Thread thread;
private Coroutine coroutine;

CoroutineExecutor() {
thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (thread) {
while (running) {
try {
if (!coroutine.finished) {
coroutine.runnable.run();
}
} catch (CoroutineDeath | Exception e) {
log.error("Error while running coroutine runnable", e);
}
finally {
coroutine.finished = true;
coroutine.returnValue = null;
thread.notifyAll();
try {
thread.wait();
} catch (InterruptedException e) {
log.error("Error while waiting for coroutine runnable", e);
Thread.currentThread().interrupt();
}
}
}
}
}
});
thread.setDaemon(true);
coroutine = new Coroutine(new Runnable() {
@Override
public void run() { }
});
coroutine.finished = true;
}

Object resume() {
synchronized (thread) {
if (thread.getState() == Thread.State.NEW) {
thread.start();
}
thread.notifyAll();
try {
thread.wait();
} catch (InterruptedException e) {
throw new InternalCoroutineException("Thread was interrupted while waiting for coroutine to yield.");
}
return coroutine.returnValue;
}
}

void yield(Object o) {
synchronized (thread) {
coroutine.returnValue = o;
thread.notifyAll();
try {
thread.wait();
} catch (InterruptedException interrupted) {
throw new CoroutineDeath();
}
}
}

void setCoroutine(Coroutine coroutine) {
synchronized (thread) {
if (busy()) {
throw new InternalCoroutineException("Coroutine assigned to a busy executor.");
}
this.coroutine = coroutine;
}
}

boolean busy() {
synchronized (Coroutine.class) {
return !coroutine.finished;
}
}

void reset() {
synchronized (thread) {
coroutine.finished = true;
if (thread.getState() != Thread.State.NEW) {
thread.interrupt();
try {
thread.wait();
} catch (InterruptedException e) {
log.error("Error while waiting for coroutine runnable", e);
Thread.currentThread().interrupt();
}
}
}
}

void kill() {
synchronized (thread) {
running = false;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
log.error("Error while waiting for coroutine runnable", e);
Thread.currentThread().interrupt();
}
}
}

@Override
public String toString() {
return "Executor " + thread.getName();
}
}

private Coroutine(Runnable runnable) {
this.runnable = runnable;
this.finished = false;
}


/**
* Resumes/starts a coroutine. Return value is the object that the coroutine passed to yield
*/
public static <T> T resume(Coroutine coroutine) {

if (coroutine.finished) {
throw new DeadCoroutineException("An attempt was made to resume a dead coroutine.");
}

CoroutineExecutor executor = getExecutorForCoroutine(coroutine);

if(executor != null) {
if (executor.equals(getCurrentExecutor())) {
throw new ResumeSelfCoroutineException("A coroutine cannot resume itself.");
}
return (T) executor.resume();
}
else {
log.error("CoroutineExcutor is null");
return null;
}
}


/**
* A coroutine can use this to return a value to whatever called resume
*/
public static void yield(Object o) {

CoroutineExecutor coroutineExecutor = getCurrentExecutor();
if (coroutineExecutor != null) {
Coroutine coroutine = coroutineExecutor.coroutine;

if (coroutine == null) {
throw new YieldOutsideOfCoroutineException("Yield cannot be used outside of a coroutine.");
}

coroutineExecutor.yield(o);
} else {
log.error("CoroutineExcutor is null");
}

}


/**
* Creates a new coroutine that with the "body" of runnable, doesn't start until resume is used
*/
public static synchronized Coroutine create(Runnable runnable) {
Coroutine coroutine = new Coroutine(runnable);
CoroutineExecutor coroutineExecutor = getFreeExecutor();
coroutineExecutor.setCoroutine(coroutine);

return coroutine;
}


/**
* Stops and cleans up the coroutine
*/
public static synchronized void destroy(Coroutine coroutine) {
CoroutineExecutor executor = getExecutorForCoroutine(coroutine);
if (executor != null) {
executor.reset();
}
}

/**
* Returns true if resuming this coroutine is possible
*/
public static synchronized boolean alive(Coroutine coroutine) {
return coroutine != null && !coroutine.finished;
}

/**
* Shrinks the thread pool
*/
public static synchronized void cleanup() {
Iterator<CoroutineExecutor> it = executorPool.iterator();
while (it.hasNext()) {
CoroutineExecutor executor = it.next();
if (!executor.busy()) {
executor.kill();
it.remove();
}

}
}

/**
* Returns the current number of executors in the pool
*/
public static synchronized int poolSize() {
return executorPool.size();
}

private static synchronized CoroutineExecutor getCurrentExecutor() {
for (CoroutineExecutor e : executorPool) {
if (Thread.currentThread().equals(e.thread)) {
return e;
}
}
return null;
}

private static synchronized CoroutineExecutor getFreeExecutor() {
for (CoroutineExecutor executor : executorPool) {
if (!executor.busy()) {
return executor;
}
}
CoroutineExecutor newExecutor = new CoroutineExecutor();
executorPool.add(newExecutor);
return newExecutor;
}

private static synchronized CoroutineExecutor getExecutorForCoroutine(Coroutine coroutine) {
for (CoroutineExecutor executor : executorPool) {
if (coroutine.equals(executor.coroutine)) {
return executor;
}
}
return null;
}
}

最后是主线程中的游戏循环,由于恢复锁定协程线程对象而卡住:

public boolean update() {
Coroutine coroutine = coroutineQueue.peek();
if (coroutine != null) {
if (Coroutine.alive(coroutine)) {
Event event = Coroutine.resume(coroutine);
if (event != null) {
broadcast(event);
}
} else {
coroutineQueue.poll();
}
}
return !coroutineQueue.isEmpty();
}

请就如何更正同步提出建议,以便在一天结束时,主循环不会被锁定,所有其他协程将按顺序正确执行,并在需要时暂停/继续。

感谢大家花时间阅读这个问题。亲切的问候

最佳答案

如果您不为synchronized 关键字提供锁,则默认使用该对象。但是,在你的例子中,这些都是静态方法,所以它使用类作为锁。因此,您所有的协程方法都锁定在同一事物上 - Coroutine 类。

关于Java 同步问题 - 主线程被协程实现锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55630880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com