|
| 1 | +package com.github.elebras1.flecs.examples.components; |
| 2 | + |
| 3 | + |
| 4 | +import com.github.elebras1.flecs.*; |
| 5 | +import com.github.elebras1.flecs.util.FlecsConstants; |
| 6 | + |
| 7 | +import java.util.Map; |
| 8 | +import java.util.concurrent.ConcurrentHashMap; |
| 9 | +import java.util.concurrent.ExecutorService; |
| 10 | +import java.util.concurrent.Executors; |
| 11 | +import java.util.concurrent.Future; |
| 12 | +import java.util.concurrent.atomic.AtomicLong; |
| 13 | + |
| 14 | +public class TaskThreadExample { |
| 15 | + |
| 16 | + private static final int NUMBER_THREADS = 4; |
| 17 | + |
| 18 | + public static void main(String[] args) { |
| 19 | + ExecutorService executor = Executors.newFixedThreadPool(NUMBER_THREADS); |
| 20 | + Map<Long, Future<?>> futures = new ConcurrentHashMap<>(); |
| 21 | + AtomicLong counter = new AtomicLong(); |
| 22 | + |
| 23 | + OsApi osApi = new OsApi(); |
| 24 | + osApi.taskNew(task -> { |
| 25 | + long id = counter.incrementAndGet(); |
| 26 | + futures.put(id, executor.submit(task)); |
| 27 | + return id; |
| 28 | + }) |
| 29 | + .taskJoin(id -> { |
| 30 | + try { |
| 31 | + futures.remove(id).get(); |
| 32 | + } catch (Exception e) { |
| 33 | + Thread.currentThread().interrupt(); |
| 34 | + } |
| 35 | + }) |
| 36 | + .set(); |
| 37 | + |
| 38 | + try (World world = new World()) { |
| 39 | + world.setTaskThreads(NUMBER_THREADS); |
| 40 | + world.component(Health.class); |
| 41 | + |
| 42 | + for(int i = 0; i < 100_000; i++) { |
| 43 | + EntityView entity = world.obtainEntityView(world.entity()); |
| 44 | + entity.set(Health.class, (HealthView health) -> health.value(100)); |
| 45 | + } |
| 46 | + |
| 47 | + world.system().with(Health.class).kind(FlecsConstants.EcsOnUpdate).multiThreaded().iter(iter -> { |
| 48 | + Field<Health> healthField = iter.field(Health.class, 0); |
| 49 | + for(int i = 0; i < iter.count(); i++) { |
| 50 | + HealthView health = healthField.getMutView(i); |
| 51 | + health.value(health.value() - 1); |
| 52 | + } |
| 53 | + }); |
| 54 | + |
| 55 | + for(int i = 0; i < 1000; i++) { |
| 56 | + world.progress(); |
| 57 | + } |
| 58 | + |
| 59 | + executor.close(); |
| 60 | + } |
| 61 | + |
| 62 | + } |
| 63 | +} |
0 commit comments