├── .gitignore ├── LICENSE ├── README.md ├── docs └── ScalabilityChart.png ├── pom.xml └── src ├── main ├── java │ └── org │ │ └── sync │ │ ├── Life.java │ │ ├── NoSyncLife.java │ │ ├── NoWaitLife.java │ │ ├── OrdinaryLife.java │ │ └── RLE.java └── resources │ └── DecimalCounter.rle └── test └── java └── org └── sync └── LifeTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Maven 2 | target/ 3 | 4 | # IntelliJ 5 | .idea/ 6 | *.iml 7 | 8 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 9 | hs_err_pid* 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Order from Chaos 2 | 3 | Koyaanisqatsi (Chaotic Life) is a research project that: 4 | * demonstrates how deterministic behavior could emerge from blind random interactions of parallel processes; 5 | * introduces a working dynamic error correction code for a universal computation model; 6 | * presents an asynchronous parallel wait-free unsynchronized implementation of [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life), or a generic cellular automaton. 7 | 8 | Here is a technical introduction: 9 | 10 | ### Synchronous vs. Asynchronous 11 | A straightforward implementation of Life takes two arrays, initializes one to the initial state, then computes the new states of all cells in the other array, swaps the arrays, computes next generation of states in the first array, and so on. If all cell states in generation *t* are computed before any state in generation *t+1*, such implementation is synchronous. In other words, the internal time of Life is fully aligned with the external time of implementation (it's these two times that are synchronous). 12 | On the other hand, an asynchronous implementation allows for an arbitrary ordering of updates of two separate cells if, and only if, those updates are causally independent. A *t+1*-th update of a cell must happen after the *t*-th update of any of its neighbor cell, but if the two are far apart, the order of updates can be any. 13 | 14 | There is some analogy here with breadth-first and depth-first search algorithms and the latter hints at how asynchronous updates can be implemented with some room for randomness ("real" or pseudo). 15 | Another analogy is with the idea of the "global clock": the synchronous approach implements it, the asynchronous one rejects it. 16 | 17 | ### Serial vs. Parallel 18 | If we want to parallelize our algorithms we find that the synchronous one is "embarrassingly parallel" within one generation of updates but imposes a barrier for all parallel processes between two generations. It's a straightforward parallelization approach to a straightforward synchronous implementation (see [OrdinaryLife.java](src/main/java/org/sync/OrdinaryLife.java)). One thing is obvious: such implementation won't scale: just imagine a parallel computer the size of the Solar system and what it would take to reach a barrier for all its parallel computations - I'll call it the Solar system scalability test. 19 | 20 | The asynchronous approach is trickier to parallelize but if you are familiar with Go you can imagine a network of go-routines and channels that will express all concurrency there is in Life. Will it pass the Solar system scalability test? Yes, but on one condition: if all your communicating serial processes are physical. We can easily create millions of go-routines on contemporary computers but we still have only so many cores and to execute our highly concurrent program we need to dynamically map our cores to our go-routines. In other words, we need a scheduler. And the problem is that it's very difficult for a scheduler to figure out which go-routine can make real progress, so, many of them will be allowed to run on a physical core only to find out that they still don't have enough input to compute their next state and have to loop back on the blocking select. The actual process, an OS thread, will never block but it will be running through lots of unnecessary switching to incomplete go-routines. Can we do better? 21 | 22 | ### Blocking vs. Wait-free 23 | Yes, we can, if we implement our parallel asynchronous algorithm in a wait-free fashion (see [NoWaitLife.java](src/main/java/org/sync/NoWaitLife.java)). All physical cores would always be busy updating cells as there is always enough work in Life (assuming the number of cores is much less than the size of the state). In some sense, such algorithm would implement a perfect scheduler which would always run only those cells that are ready for state update. In order to ensure correctness of our computation, we would naturally rely on the atomic Compare-And-Swap machine instruction readily available in all modern CPUs. No busy waits, no simulated locks nor semaphores - just atomic conditional updates of shared memory locations. 24 | 25 | Our next problem is that now every cell update involves many atomic operations (working with blocks of cells is just a constant factor from scalability perspective). What that means is that all local caches are for nothing. A CPU has to go straight to shared memory and make sure it can perform its read-and-write cycle with no interference from other CPUs. Whichever way this is achieved - locks pushed down to memory blocks, cache coherence protocols, or whatnot - we know synchronization is in our way. 26 | 27 | ### Synchronized vs. Unsynchronized 28 | We always want to minimize synchronization between parallel processes but can we totally eliminate it? Not in [Apple's way](https://developer.apple.com/library/content/samplecode/DispatchLife/Listings/DispatchLife_c.html), of course: 29 | 30 | DispatchLife.c 31 | > Due to the highly asynchronous nature of this implementation, the 32 | > simulation's results may differ from the classic version for the same 33 | > set of initial conditions. In particular, due to non-deterministic 34 | > scheduling factors, the same set of initial conditions is likely to 35 | > produce dramatically different results on subsequent simulations. 36 | 37 | Can we eliminate synchronization, so that we wouldn't compromise correctness for more parallelism and better performance (not as dumb a trade-off as it may sound, but certainly not so much correctness)? Unsynchronized access to shared memory leads to data races - arguably the nastiest bugs in parallel programs. Can we compute reliably with data races? To the best of my knowledge the answer so far has been a firm no. If the answer is wrong, what could possibly undo the devastating effect of data races at scale? If two threads are simultaneously writing the same value to the same memory location, such data race is harmless. If one thread delays, however, the value may become obsolete and we'll need a way to detect and fix the error. To be able to do that we need to introduce redundancy into our computational process. If I were to describe my solution in one sentence, it would be "an error correcting code unfolding in time as computation". 38 | 39 | So, here it is, an "asynchronous parallel wait-free unsynchronized" implementation of Life (see [NoSyncLife.java](src/main/java/org/sync/NoSyncLife.java)). Of course, this is just a proof of concept. How reliable is it? It's probably too soon to try to answer this question. The presented implementation does not achieve the full potential of the code but, I believe, is good enough to start a conversation. 40 | 41 | ![Scalability chart](docs/ScalabilityChart.png?raw=true) 42 | 43 | ## How to build, test, and run 44 | 45 | The project uses Java 8 and Maven (3.3.9), though it doesn't really have any dependencies. 46 | To run tests: 47 | ``` 48 | mvn test 49 | ``` 50 | To run indefinite tests, comment out the @Ignore annotation for testInfiniteNoSync() in [LifeTest.java](src/test/java/org/sync/LifeTest.java). 51 | 52 | To run visualization, do one of the following: 53 | ```shell 54 | mvn exec:java # NoSyncLife, Acorn pattern 55 | mvn exec:java@counter # NoSyncLife, DecimalCounter pattern 56 | mvn exec:java@acorn2 # NoWaitLife, Acorn pattern 57 | mvn exec:java@counter2 # NoWaitLife, DecimalCounter pattern 58 | mvn exec:java@acorn3 # OrdinaryLife, Acorn pattern 59 | mvn exec:java@counter3 # OrdinaryLife, DecimalCounter pattern 60 | ``` 61 | To create a jar file: 62 | ```shell 63 | man package 64 | ``` 65 | To run from jar: 66 | ```shell 67 | java -jar target/ChaoticLife-1.0.0.jar [-T NOSYNC|NOWAIT|ORDINARY] [-w width] [-h height] [-t generations] [-p threads] [-novis] [.rle] 68 | ``` 69 | 70 | ## How to build, test, and run without Maven 71 | 72 | To build 73 | ```shell 74 | mkdir -p target/classes 75 | javac -sourcepath src/main/java -d target/classes src/main/java/org/sync/*.java 76 | ``` 77 | To run visualization 78 | ```shell 79 | java -cp target/classes org.sync.NoSyncLife -t 10000 -p 8 80 | java -cp target/classes org.sync.NoSyncLife -t 10000 -p 8 -w 860 -h 1400 src/main/resources/DecimalCounter.rle 81 | java -cp target/classes org.sync.NoWaitLife -t 10000 -p 8 -w 860 -h 1400 src/main/resources/DecimalCounter.rle 82 | java -cp target/classes org.sync.OrdinaryLife -t 10000 -p 8 -w 860 -h 1400 src/main/resources/DecimalCounter.rle 83 | ``` 84 | To test 85 | ```shell 86 | java -cp target/classes org.sync.OrdinaryLife -t 10000 -novis > golden 87 | while (true) do java -cp target/classes org.sync.NoSyncLife -t 10000 -p 8 -novis > current && diff golden current; done 88 | ``` 89 | 90 | ## License 91 | 92 | Koyaanisqatsi (Chaotic Life) is licensed under the Apache License, Version 2.0. 93 | 94 | For additional information, see the [LICENSE](LICENSE) file. 95 | 96 | -------------------------------------------------------------------------------- /docs/ScalabilityChart.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OlegMazurov/Koyaanisqatsi/12efd58da247d1974040d960a9be110eaee27e2f/docs/ScalabilityChart.png -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | org.sync.ChaoticLife 5 | ChaoticLife 6 | 1.0.0 7 | ${project.artifactId} 8 | Koyaanisqatsi (Chaotic Life) 9 | 10 | 11 | 1.8 12 | 1.8 13 | UTF-8 14 | 15 | 16 | 17 | 18 | junit 19 | junit 20 | 4.12 21 | test 22 | 23 | 24 | 25 | 26 | 27 | 28 | org.apache.maven.plugins 29 | maven-jar-plugin 30 | 3.0.2 31 | 32 | 33 | 34 | org.sync.Life 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.codehaus.mojo 42 | exec-maven-plugin 43 | 1.6.0 44 | 45 | 46 | default-cli 47 | 48 | org.sync.Life 49 | -w 400 -h 400 -t 8000 -p 8 50 | 51 | 52 | 53 | counter 54 | 55 | org.sync.Life 56 | -h 1400 -w 860 -t 20000 -p 8 DecimalCounter.rle 57 | 58 | 59 | 60 | acorn2 61 | 62 | org.sync.NoWaitLife 63 | -w 400 -h 400 -t 8000 -p 8 64 | 65 | 66 | 67 | counter2 68 | 69 | org.sync.NoWaitLife 70 | -h 1400 -w 860 -t 20000 -p 8 DecimalCounter.rle 71 | 72 | 73 | 74 | acorn3 75 | 76 | org.sync.OrdinaryLife 77 | -w 400 -h 400 -t 8000 -p 8 78 | 79 | 80 | 81 | counter3 82 | 83 | org.sync.OrdinaryLife 84 | -h 1400 -w 860 -t 20000 -p 8 DecimalCounter.rle 85 | 86 | 87 | 88 | 89 | 90 | 91 | maven-clean-plugin 92 | 3.0.0 93 | 94 | 95 | 96 | clean 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /src/main/java/org/sync/Life.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Oleg Mazurov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.sync; 18 | 19 | import javax.swing.*; 20 | import java.awt.*; 21 | import java.awt.event.WindowAdapter; 22 | import java.awt.event.WindowEvent; 23 | import java.awt.image.BufferedImage; 24 | import java.awt.image.DataBufferInt; 25 | 26 | /** 27 | * Chaotic Life 28 | * 29 | * https://github.com/OlegMazurov/Koyaanisqatsi 30 | * 31 | */ 32 | 33 | public abstract class Life { 34 | 35 | public enum Type { ORDINARY, NOSYNC, NOWAIT }; 36 | protected static final int STATE0 = 0; 37 | protected static final int STATE1 = 1; 38 | protected static final int T0 = 0; 39 | private static final int[] COLORS = { 40 | 0xff8000, 0xffffff, 0xff0000, 0x00ff00, 41 | 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, 42 | }; 43 | 44 | protected static Type type = Type.NOSYNC; 45 | 46 | protected final int Width; 47 | protected final int Height; 48 | protected final int maxTime; 49 | protected final int nThreads; 50 | 51 | private final boolean vis; 52 | private int[] imgData; 53 | 54 | public abstract void execute(); 55 | 56 | protected abstract int getState(int row, int col); 57 | 58 | protected void setColor(int idx, int color) { 59 | if (vis) { 60 | imgData[idx] = color == 0 ? 0 : COLORS[color % COLORS.length]; 61 | } 62 | } 63 | 64 | protected Life(int w, int h, int t, int p, boolean v) { 65 | Width = w; 66 | Height = h; 67 | maxTime = T0 + t; 68 | nThreads = p; 69 | vis = v; 70 | 71 | // Initialize visualization 72 | if (vis) { 73 | BufferedImage img = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB); 74 | imgData = ((DataBufferInt)img.getRaster().getDataBuffer()).getData(); 75 | 76 | JFrame frame = new JFrame() { 77 | public void paint(Graphics g) { 78 | g.drawImage(img, 0, 0, getWidth(), getHeight(), null); 79 | } 80 | }; 81 | frame.setSize(Width, Height); 82 | frame.addWindowListener(new WindowAdapter() { 83 | public void windowClosing(WindowEvent e) { 84 | System.exit(0); 85 | } 86 | }); 87 | frame.setVisible(true); 88 | 89 | Timer timer = new Timer(40, (e) -> frame.repaint()); 90 | timer.start(); 91 | } 92 | } 93 | 94 | public static Life fromRLE(RLE rle, Type type, int width, int height, int time, int par, boolean vis) 95 | { 96 | // Re-center 97 | width = Math.max(width, rle.getW()); 98 | height = Math.max(height, rle.getH()); 99 | int[] state = new int[width * height]; 100 | int x0 = (width - rle.getW()) / 2; 101 | int y0 = (height - rle.getH()) / 2; 102 | for (int x = 0; x < rle.getW(); ++x) { 103 | for (int y = 0; y < rle.getH(); ++y) { 104 | state[(y + y0) * width + x + x0] = rle.getState(x, y); 105 | } 106 | } 107 | 108 | Life res = null; 109 | switch (type) { 110 | case ORDINARY: 111 | res = new OrdinaryLife(width, height, time, par, vis, state); 112 | break; 113 | case NOSYNC: 114 | res = new NoSyncLife(width, height, time, par, vis, state); 115 | break; 116 | case NOWAIT: 117 | res = new NoWaitLife(width, height, time, par, vis, state); 118 | break; 119 | default: 120 | System.err.println("ERROR: unknown type: " + type); 121 | System.exit(1); 122 | } 123 | return res; 124 | } 125 | 126 | public static Life fromRLE(RLE rle, Type type, int time, int par, boolean vis) 127 | { 128 | return fromRLE(rle, type, rle.getW(), rle.getH(), time, par, vis); 129 | } 130 | 131 | public String[] getResult() { 132 | String[] result = new String[Height]; 133 | StringBuilder sb = new StringBuilder(); 134 | for (int r = 0; r < Height; ++r) { 135 | sb.setLength(0); 136 | for (int c = 0; c < Width; ++c) { 137 | sb.append(getState(r, c)); 138 | } 139 | result[r] = sb.toString(); 140 | } 141 | return result; 142 | } 143 | 144 | public static void main(String[] args) 145 | { 146 | int width = 0; 147 | int height = 0; 148 | int time = 10000; 149 | int parallelism = Runtime.getRuntime().availableProcessors(); 150 | boolean vis = true; 151 | RLE rle = null; 152 | 153 | for (int i = 0; i < args.length; i++) { 154 | if (args[i].equals("-w")) { 155 | width = Integer.parseInt(args[++i]); 156 | } 157 | else if (args[i].equals("-h")) { 158 | height = Integer.parseInt(args[++i]); 159 | } 160 | else if (args[i].equals("-p")) { 161 | parallelism = Integer.parseInt(args[++i]); 162 | } 163 | else if (args[i].equals("-t")) { 164 | time = Integer.parseInt(args[++i]); 165 | } 166 | else if (args[i].equals("-T")) { 167 | type = Type.valueOf(args[++i]); 168 | } 169 | else if (args[i].equals("-novis")) { 170 | vis = false; 171 | } 172 | else { 173 | rle = RLE.fromFile(args[i]); 174 | if (rle == null) { 175 | return; 176 | } 177 | } 178 | } 179 | 180 | if (rle == null) { 181 | rle = RLE.getAcorn(); 182 | } 183 | 184 | Life lf = fromRLE(rle, type, width, height, time, parallelism, vis); 185 | long start = System.currentTimeMillis(); 186 | lf.execute(); 187 | long end = System.currentTimeMillis(); 188 | 189 | String[] state = lf.getResult(); 190 | for (String str : state) { 191 | System.out.println(str); 192 | } 193 | System.out.println("Score: " + (1000l * time * lf.Width * lf.Height / (end-start)) + " ops/sec"); 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/main/java/org/sync/NoSyncLife.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Oleg Mazurov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.sync; 18 | 19 | /** 20 | * Asynchronous parallel wait-free unsynchronized implementation of Life 21 | * 22 | * https://github.com/OlegMazurov/Koyaanisqatsi 23 | * 24 | */ 25 | 26 | public class NoSyncLife extends Life { 27 | 28 | private final Cell[] cells; 29 | 30 | private static class Cell { 31 | int idx; 32 | int[] state; 33 | Cell[] neighbors; 34 | 35 | public Cell(int i, int s) { 36 | idx = i; 37 | state = new int[3]; 38 | int off = T0 & 0x1; 39 | state[1 - off] = (T0 - 1) << 1; 40 | state[off] = (T0 << 1) | s; 41 | neighbors = new Cell[8]; 42 | } 43 | } 44 | 45 | protected int getState(int row, int col) { 46 | Cell cell = cells[row * Width + col]; 47 | return Math.max(cell.state[0], cell.state[1]) & 0x1; 48 | } 49 | 50 | private static class PseudoRandom { 51 | static final int FACTOR1 = 2999; 52 | static final int FACTOR2 = 7901; 53 | int val; 54 | 55 | PseudoRandom(int seed) { 56 | val = seed; 57 | } 58 | 59 | int nextInt(int n) { 60 | if (n <= 1) return 0; 61 | val = Math.abs(val * FACTOR1 + FACTOR2); 62 | return val % n; 63 | } 64 | } 65 | 66 | private void runUnsync(int id) 67 | { 68 | PseudoRandom rnd = new PseudoRandom(id); 69 | Cell[] next = new Cell[16]; 70 | 71 | // Start apart 72 | Cell cur = cells[cells.length * id / nThreads]; 73 | 74 | mainLoop: 75 | for (;;) { 76 | int s0 = cur.state[0]; 77 | int s1 = cur.state[1]; 78 | int S0 = Math.min(s0, s1); 79 | int S1 = Math.max(s0, s1); 80 | int S2 = cur.state[2]; 81 | 82 | int TS0 = S0 >> 1; 83 | int TS1 = S1 >> 1; 84 | int TS2 = S2 >> 1; 85 | 86 | if (TS2 < TS1) { 87 | int off = TS1 & 0x1; 88 | int cnt = 0; 89 | int V = S1; 90 | for (Cell neighbor : cur.neighbors) { 91 | int val = neighbor.state[off]; 92 | if ((val >> 1) == TS1) { 93 | V ^= val; 94 | } 95 | else { 96 | next[cnt++] = neighbor; 97 | } 98 | } 99 | if (cnt == 0) { 100 | cur.state[2] = V; 101 | cur = cells[cur.idx + 1 == cells.length ? 0 : cur.idx + 1]; 102 | continue mainLoop; 103 | } 104 | 105 | if (TS2 < TS0) { 106 | cnt = 0; 107 | off = TS0 & 0x1; 108 | V = S0; 109 | for (Cell neighbor : cur.neighbors) { 110 | int val = neighbor.state[off]; 111 | if ((val >> 1) == TS0) { 112 | V ^= val; 113 | } 114 | else { 115 | next[cnt++] = neighbor; 116 | } 117 | } 118 | if (cnt == 0) { 119 | cur.state[2] = V; 120 | continue mainLoop; 121 | } 122 | } 123 | else if (TS2 == TS0) { 124 | cnt = 0; 125 | off = TS0 & 0x1; 126 | V = S0 ^ S2; 127 | for (Cell neighbor : cur.neighbors) { 128 | int val = neighbor.state[off]; 129 | if ((val >> 1) == TS0) { 130 | V ^= val; 131 | } 132 | else { 133 | next[cnt++] = neighbor; 134 | } 135 | } 136 | if (cnt == 1) { 137 | next[0].state[off] = V; 138 | continue mainLoop; 139 | } 140 | } 141 | else { 142 | cnt = 0; 143 | next[cnt++] = cur; 144 | off = TS2 & 0x1; 145 | V = S2; 146 | for (Cell neighbor : cur.neighbors) { 147 | int val = neighbor.state[off]; 148 | if ((val >> 1) == TS2) { 149 | V ^= val; 150 | } 151 | else { 152 | next[cnt++] = neighbor; 153 | } 154 | } 155 | if (cnt == 1) { 156 | next[0].state[off] = V; 157 | continue mainLoop; 158 | } 159 | } 160 | cur = next[rnd.nextInt(cnt)]; 161 | } 162 | else if (TS2 == TS1) { 163 | int off = TS2 & 0x1; 164 | int cnt = 0; 165 | int sum = 0; 166 | 167 | int V = S1 ^ S2; 168 | for (Cell neighbor : cur.neighbors) { 169 | int val = neighbor.state[off]; 170 | if ((val >> 1) == TS2) { 171 | V ^= val; 172 | sum += val & 0x1; 173 | } 174 | else { 175 | next[cnt++] = neighbor; 176 | } 177 | } 178 | if (cnt == 1) { 179 | next[0].state[off] = V; 180 | sum += V & 0x1; 181 | cnt = 0; 182 | } 183 | 184 | int cnt2 = cnt; 185 | Cell rnext = null; 186 | for (Cell neighbor : cur.neighbors) { 187 | int val = neighbor.state[2]; 188 | if ((val >> 1) <= TS2) { 189 | if ((val >> 1) < TS2) { 190 | ++cnt2; 191 | rnext = neighbor; 192 | } 193 | if (cnt > 0) { 194 | next[cnt++] = neighbor; 195 | } 196 | } 197 | } 198 | if (cnt2 > 0) { 199 | cur = rnext != null ? rnext : next[rnd.nextInt(cnt)]; 200 | continue mainLoop; 201 | } 202 | 203 | // Are we done? 204 | if (TS1 == maxTime) { 205 | int idx = cur.idx; 206 | for (int n = 0; n < cells.length; ++n) { 207 | if (++idx == cells.length) idx = 0; 208 | cur = cells[idx]; 209 | if (Math.max(cur.state[0], cur.state[1]) >> 1 != maxTime) continue mainLoop; 210 | } 211 | return; 212 | } 213 | 214 | // Apply the rule of Life 215 | int nextState = sum < 2 ? STATE0 : sum == 2 ? (S1 & 0x1) : sum == 3 ? STATE1 : STATE0; 216 | cur.state[1 - off] = ((TS1 + 1) << 1) | nextState; 217 | 218 | // Color live cells according to the current thread id 219 | setColor(cur.idx, nextState == STATE0 ? 0 : id + 1); 220 | // Color all cells according to the current thread id 221 | //setColor(cur.idx, id + 1); 222 | // Color all cells according to the current generation 223 | //setColor(cur.idx, TS1); 224 | cur = cells[cur.idx + 1 == cells.length ? 0 : cur.idx + 1]; 225 | } 226 | else { 227 | int off = TS2 & 0x1; 228 | int cnt = 0; 229 | int V = S2; 230 | for (Cell neighbor : cur.neighbors) { 231 | int val = neighbor.state[off]; 232 | if ((val >> 1) == TS2) { 233 | V ^= val; 234 | } 235 | else { 236 | cnt++; 237 | break; 238 | } 239 | } 240 | if (cnt == 0) { 241 | cur.state[off] = V; 242 | continue mainLoop; 243 | } 244 | 245 | off = TS1 & 0x1; 246 | int sum = 0; 247 | for (Cell neighbor : cur.neighbors) { 248 | int val = neighbor.state[off]; 249 | if ((val >> 1) == TS1) { 250 | sum += val & 0x1; 251 | } 252 | else { 253 | continue mainLoop; 254 | } 255 | } 256 | 257 | // Apply the rule of Life 258 | int nextState = sum < 2 ? STATE0 : sum == 2 ? (S1 & 0x1) : sum == 3 ? STATE1 : STATE0; 259 | cur.state[1 - off] = ((TS1 + 1) << 1) | nextState; 260 | } 261 | } 262 | } 263 | 264 | public void execute() 265 | { 266 | // Run concurrently 267 | Thread[] threads = new Thread[nThreads]; 268 | for (int t = 0; t < threads.length; ++t) { 269 | final int id = t; 270 | Thread thread = new Thread(() -> runUnsync(id)); 271 | threads[t] = thread; 272 | thread.start(); 273 | } 274 | 275 | try { 276 | for (Thread thread : threads) { 277 | thread.join(); 278 | } 279 | } 280 | catch (InterruptedException ie) { 281 | ie.printStackTrace(); 282 | } 283 | } 284 | 285 | /** 286 | * Cell neighbors wrapped around a torus: 287 | * ------------- 288 | * +1 | 6 | 5 | 4 | 289 | * ------------- 290 | * r | 7 | | 3 | 291 | * ------------- 292 | * -1 | 0 | 1 | 2 | 293 | * ------------- 294 | * -1 c +1 295 | */ 296 | private int getNeighbor(int idx, int i) 297 | { 298 | int r = idx / Width; 299 | int c = idx % Width; 300 | switch (i) { 301 | case 0: 302 | if (--c < 0) c += Width; 303 | case 1: 304 | if (--r < 0) r += Height; 305 | break; 306 | case 2: 307 | if (--r < 0) r += Height; 308 | case 3: 309 | if (++c == Width) c = 0; 310 | break; 311 | case 4: 312 | if (++c == Width) c = 0; 313 | case 5: 314 | if (++r == Height) r = 0; 315 | break; 316 | case 6: 317 | if (++r == Height) r = 0; 318 | case 7: 319 | if (--c < 0) c += Width; 320 | break; 321 | } 322 | return r * Width + c; 323 | } 324 | 325 | public NoSyncLife(int w, int h, int t, int p, boolean v, int[] s) 326 | { 327 | super(w, h, t, p, v); 328 | 329 | // Initialize cells 330 | cells = new Cell[Width * Height]; 331 | for (int idx = 0; idx < cells.length; ++idx) { 332 | Cell cell = new Cell(idx, s[idx] == 0 ? STATE0 : STATE1); 333 | cells[idx] = cell; 334 | } 335 | for (Cell cell : cells) { 336 | int S = cell.state[T0 & 0x1]; 337 | cell.state[2] ^= S; 338 | for (int n = 0; n < cell.neighbors.length; ++n) { 339 | int nidx = getNeighbor(cell.idx, n); 340 | Cell neighbor = cells[nidx]; 341 | cell.neighbors[n] = neighbor; 342 | neighbor.state[2] ^= S; 343 | } 344 | } 345 | } 346 | 347 | public static void main(String[] args) { 348 | type = Type.NOSYNC; 349 | Life.main(args); 350 | } 351 | } 352 | -------------------------------------------------------------------------------- /src/main/java/org/sync/NoWaitLife.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Oleg Mazurov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.sync; 18 | 19 | import java.util.concurrent.CountDownLatch; 20 | import java.util.concurrent.ForkJoinPool; 21 | import java.util.concurrent.ForkJoinTask; 22 | import java.util.concurrent.atomic.AtomicInteger; 23 | 24 | 25 | /** 26 | * Asynchronous parallel wait-free implementation of Life 27 | * 28 | * https://github.com/OlegMazurov/Koyaanisqatsi 29 | * 30 | */ 31 | 32 | public class NoWaitLife extends Life { 33 | 34 | private final Cell[] cells; 35 | private CountDownLatch finished; 36 | 37 | protected int getState(int row, int col) { 38 | Cell cell = cells[row * Width + col]; 39 | if (cell.time < cell.neighbors[0].time) { 40 | cell = cell.neighbors[0]; 41 | } 42 | return cell.state; 43 | } 44 | 45 | private class Cell extends ForkJoinTask 46 | { 47 | private int idx; 48 | private int state; 49 | private int time; 50 | private Cell[] neighbors; 51 | private AtomicInteger count; 52 | 53 | public Cell(int i, int s) 54 | { 55 | idx = i; 56 | state = s; 57 | time = 0; 58 | neighbors = new Cell[9]; 59 | count = new AtomicInteger(neighbors.length); 60 | } 61 | 62 | /* Not used */ 63 | public Object getRawResult() { return null; } 64 | protected void setRawResult(Object value) {} 65 | 66 | protected boolean exec() { 67 | state = neighbors[0].state; 68 | time = neighbors[0].time + 1; 69 | int sum = 0; 70 | for (int i = 1; i < neighbors.length; ++i) { 71 | if (neighbors[i].state == STATE1) { 72 | sum += 1; 73 | } 74 | } 75 | 76 | // Apply the rule of Life 77 | if (sum < 2 || sum > 3) { 78 | state = STATE0; 79 | } 80 | else if (sum == 3) { 81 | state = STATE1; 82 | } 83 | 84 | // Color live cells according to the current thread id 85 | setColor(idx, state == STATE0 ? 0 : (int)Thread.currentThread().getId()); 86 | // Color all cells according to the current thread id 87 | //setColor(idx, (int)Thread.currentThread().getId()) 88 | // Color all cells according to the current generation 89 | //setColor(idx, TS1); 90 | 91 | reinitialize(); 92 | count.set(neighbors.length); 93 | if (time == maxTime) { 94 | finished.countDown(); 95 | } 96 | else { 97 | for (Cell cell : neighbors) { 98 | if (cell.count.addAndGet(-1) == 0) { 99 | cell.fork(); 100 | } 101 | } 102 | } 103 | 104 | return false; 105 | } 106 | } 107 | 108 | public void execute() 109 | { 110 | finished = new CountDownLatch(Width * Height); 111 | 112 | ForkJoinPool pool = new ForkJoinPool( 113 | nThreads, 114 | ForkJoinPool.defaultForkJoinWorkerThreadFactory, 115 | (t,e) -> e.printStackTrace(), 116 | false); 117 | 118 | for (Cell cell : cells) { 119 | pool.execute(cell.neighbors[0]); 120 | } 121 | 122 | try { 123 | finished.await(); 124 | } 125 | catch (InterruptedException ex) { 126 | ex.printStackTrace(); 127 | } 128 | pool.shutdown(); 129 | } 130 | 131 | private int getNeighbor(int r, int c, int i) 132 | { 133 | switch (i) { 134 | case 1: 135 | if (--c < 0) c += Width; 136 | case 2: 137 | if (--r < 0) r += Height; 138 | break; 139 | case 3: 140 | if (--r < 0) r += Height; 141 | case 4: 142 | if (++c == Width) c = 0; 143 | break; 144 | case 5: 145 | if (++c == Width) c = 0; 146 | case 6: 147 | if (++r == Height) r = 0; 148 | break; 149 | case 7: 150 | if (++r == Height) r = 0; 151 | case 8: 152 | if (--c < 0) c += Width; 153 | break; 154 | } 155 | return r * Width + c; 156 | } 157 | 158 | 159 | public NoWaitLife(int w, int h, int t, int p, boolean v, int[] s) 160 | { 161 | super(w, h, t, p, v); 162 | 163 | // Initialize cells 164 | cells = new Cell[Width * Height]; 165 | for (int r = 0; r < Height; ++r) { 166 | for (int c = 0; c < Width; ++c) { 167 | int idx = r * Width + c; 168 | Cell cell = new Cell(idx, s[idx] == 0 ? STATE0 : STATE1); 169 | Cell alt = new Cell(idx, 0); 170 | cell.neighbors[0] = alt; 171 | alt.neighbors[0] = cell; 172 | cells[idx] = cell; 173 | } 174 | } 175 | for (int r = 0; r < Height; ++r) { 176 | for (int c = 0; c < Width; ++c) { 177 | int idx = r * Width + c; 178 | Cell cell = cells[idx]; 179 | for (int i = 1; i < cell.neighbors.length; ++i) { 180 | Cell neighbor = cells[getNeighbor(r, c, i)].neighbors[0]; 181 | cell.neighbors[i] = neighbor; 182 | neighbor.neighbors[i + 4 > 8 ? i - 4 : i + 4] = cell; 183 | } 184 | } 185 | } 186 | } 187 | 188 | public static void main(String[] args) { 189 | type = Type.NOWAIT; 190 | Life.main(args); 191 | } 192 | 193 | } 194 | -------------------------------------------------------------------------------- /src/main/java/org/sync/OrdinaryLife.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Oleg Mazurov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.sync; 18 | 19 | import java.util.concurrent.CyclicBarrier; 20 | 21 | /** 22 | * Synchronous parallel implementation of Life 23 | * 24 | * https://github.com/OlegMazurov/Koyaanisqatsi 25 | * 26 | */ 27 | 28 | public class OrdinaryLife extends Life { 29 | 30 | private final Cell[] cells; 31 | private CyclicBarrier barrier; 32 | private boolean useAlt; 33 | 34 | protected int getState(int row, int col) { 35 | Cell cell = cells[row * Width + col]; 36 | if (useAlt) { 37 | cell = cell.neighbors[0]; 38 | } 39 | return cell.state; 40 | } 41 | 42 | private static class Cell { 43 | int state; 44 | Cell[] neighbors; 45 | 46 | public Cell(int i, int s) 47 | { 48 | state = s; 49 | neighbors = new Cell[9]; 50 | } 51 | 52 | void updateState() { 53 | state = neighbors[0].state; 54 | int sum = 0; 55 | for (int i = 1; i < neighbors.length; ++i) { 56 | if (neighbors[i].state == STATE1) { 57 | sum += 1; 58 | } 59 | } 60 | 61 | // Apply the rule of Life 62 | if (sum < 2 || sum > 3) { 63 | state = STATE0; 64 | } 65 | else if (sum == 3) { 66 | state = STATE1; 67 | } 68 | } 69 | } 70 | 71 | private void runStaticSchedule(int id) { 72 | 73 | int minIdx = (int)((long)id * cells.length / nThreads); 74 | int maxIdx = (int)((long)(id + 1) * cells.length / nThreads); 75 | 76 | for (int time = 1; time <= maxTime; ++time) { 77 | 78 | for (int idx = minIdx; idx < maxIdx; ++idx) { 79 | Cell cell = useAlt ? cells[idx] : cells[idx].neighbors[0]; 80 | cell.updateState(); 81 | 82 | // Color live cells according to the current thread id 83 | setColor(idx, cell.state == STATE0 ? 0 : id + 1); 84 | // Color all cells according to the current thread id 85 | //setColor(idx, (int)Thread.currentThread().getId()) 86 | // Color all cells according to the current generation 87 | //setColor(idx, TS1); 88 | } 89 | 90 | try { 91 | barrier.await(); 92 | } 93 | catch (Exception ex) { 94 | System.err.println("ERROR in thread " + id); 95 | ex.printStackTrace(); 96 | return; 97 | } 98 | } 99 | } 100 | 101 | public void execute() 102 | { 103 | // Run concurrently 104 | Thread[] threads = new Thread[nThreads]; 105 | for (int t = 0; t < threads.length; ++t) { 106 | final int id = t; 107 | Thread thread = new Thread(() -> runStaticSchedule(id)); 108 | threads[t] = thread; 109 | thread.start(); 110 | } 111 | 112 | try { 113 | for (Thread thread : threads) { 114 | thread.join(); 115 | } 116 | } 117 | catch (InterruptedException ie) { 118 | ie.printStackTrace(); 119 | } 120 | } 121 | 122 | private int getNeighbor(int r, int c, int i) 123 | { 124 | switch (i) { 125 | case 1: 126 | if (--c < 0) c += Width; 127 | case 2: 128 | if (--r < 0) r += Height; 129 | break; 130 | case 3: 131 | if (--r < 0) r += Height; 132 | case 4: 133 | if (++c == Width) c = 0; 134 | break; 135 | case 5: 136 | if (++c == Width) c = 0; 137 | case 6: 138 | if (++r == Height) r = 0; 139 | break; 140 | case 7: 141 | if (++r == Height) r = 0; 142 | case 8: 143 | if (--c < 0) c += Width; 144 | break; 145 | } 146 | return r * Width + c; 147 | } 148 | 149 | public OrdinaryLife(int w, int h, int t, int p, boolean v, int[] s) { 150 | super(w, h, t, p, v); 151 | 152 | // Initialize cells 153 | cells = new Cell[Width * Height]; 154 | for (int r = 0; r < Height; ++r) { 155 | for (int c = 0; c < Width; ++c) { 156 | int idx = r * Width + c; 157 | Cell cell = new Cell(idx, s[idx] == 0 ? STATE0 : STATE1); 158 | Cell alt = new Cell(idx, 0); 159 | cell.neighbors[0] = alt; 160 | alt.neighbors[0] = cell; 161 | cells[idx] = cell; 162 | } 163 | } 164 | for (int r = 0; r < Height; ++r) { 165 | for (int c = 0; c < Width; ++c) { 166 | int idx = r * Width + c; 167 | Cell cell = cells[idx]; 168 | for (int i = 1; i < cell.neighbors.length; ++i) { 169 | Cell neighbor = cells[getNeighbor(r, c, i)].neighbors[0]; 170 | cell.neighbors[i] = neighbor; 171 | neighbor.neighbors[i + 4 > 8 ? i - 4 : i + 4] = cell; 172 | } 173 | } 174 | } 175 | useAlt = false; 176 | 177 | barrier = new CyclicBarrier(nThreads, () -> { useAlt = !useAlt; }); 178 | } 179 | 180 | public static void main(String[] args) { 181 | type = Type.ORDINARY; 182 | Life.main(args); 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/main/java/org/sync/RLE.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 Oleg Mazurov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package org.sync; 18 | 19 | import java.io.*; 20 | 21 | /** 22 | * Created by olegmazurov on 7/10/17. 23 | */ 24 | public class RLE { 25 | private int w; 26 | private int h; 27 | private int[] state; 28 | 29 | public int getW() { 30 | return w; 31 | } 32 | 33 | public int getH() { 34 | return h; 35 | } 36 | 37 | public int[] getState() { 38 | return state; 39 | } 40 | 41 | public int getState(int x, int y) { 42 | return state[y * w + x]; 43 | } 44 | 45 | /* Acorn pattern: 46 | * 47 | * X 48 | * X 49 | * XX XXX 50 | */ 51 | public static RLE getAcorn() { 52 | int w = 200; 53 | int h = 200; 54 | int[] state = new int[w * h]; 55 | int start = h/2*w + w/2; 56 | state[start] = 1; 57 | state[start+1] = 1; 58 | state[start+4] = 1; 59 | state[start+5] = 1; 60 | state[start+6] = 1; 61 | state[start+w+3] = 1; 62 | state[start+2*w+1] = 1; 63 | 64 | RLE rle = new RLE(); 65 | rle.w = w; 66 | rle.h = h; 67 | rle.state = state; 68 | return rle; 69 | } 70 | 71 | public static RLE fromFile(String fname) 72 | { 73 | try { 74 | if (fname == null || fname.length() == 0) { 75 | System.err.println("ERROR: empty file name"); 76 | } 77 | char ch = fname.charAt(0); 78 | String resourceName = ch == '/' ? fname : "/" + fname; 79 | 80 | InputStream is = RLE.class.getResourceAsStream(resourceName); 81 | BufferedReader in = is != null ? new BufferedReader(new InputStreamReader(is)) : 82 | new BufferedReader(new FileReader(fname)); 83 | 84 | // Skip comments 85 | String line; 86 | for (;;) { 87 | line = in.readLine(); 88 | if (line.charAt(0) != '#') { 89 | break; 90 | } 91 | } 92 | 93 | // Parse parameters 94 | int w = 0; 95 | int h = 0; 96 | String[] tokens = line.split("[ ,]+"); 97 | for (int i=0; i