c-life.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. #include <assert.h>
  5. #include "life.h"
  6. #include "_cgo_export.h"
  7. const int MYCONST = 0;
  8. // Do the actual manipulation of the life board in C. This could be
  9. // done easily in Go, we are just using C for demonstration
  10. // purposes.
  11. void
  12. Step(int x, int y, int *a, int *n)
  13. {
  14. struct GoStart_return r;
  15. // Use Go to start 4 goroutines each of which handles 1/4 of the
  16. // board.
  17. r = GoStart(0, x, y, 0, x / 2, 0, y / 2, a, n);
  18. assert(r.r0 == 0 && r.r1 == 100); // test multiple returns
  19. r = GoStart(1, x, y, x / 2, x, 0, y / 2, a, n);
  20. assert(r.r0 == 1 && r.r1 == 101); // test multiple returns
  21. GoStart(2, x, y, 0, x / 2, y / 2, y, a, n);
  22. GoStart(3, x, y, x / 2, x, y / 2, y, a, n);
  23. GoWait(0);
  24. GoWait(1);
  25. GoWait(2);
  26. GoWait(3);
  27. }
  28. // The actual computation. This is called in parallel.
  29. void
  30. DoStep(int xdim, int ydim, int xstart, int xend, int ystart, int yend, int *a, int *n)
  31. {
  32. int x, y, c, i, j;
  33. for(x = xstart; x < xend; x++) {
  34. for(y = ystart; y < yend; y++) {
  35. c = 0;
  36. for(i = -1; i <= 1; i++) {
  37. for(j = -1; j <= 1; j++) {
  38. if(x+i >= 0 && x+i < xdim &&
  39. y+j >= 0 && y+j < ydim &&
  40. (i != 0 || j != 0))
  41. c += a[(x+i)*xdim + (y+j)] != 0;
  42. }
  43. }
  44. if(c == 3 || (c == 2 && a[x*xdim + y] != 0))
  45. n[x*xdim + y] = 1;
  46. else
  47. n[x*xdim + y] = 0;
  48. }
  49. }
  50. }