Skip to content

Instantly share code, notes, and snippets.

@dom96
Created December 22, 2011 21:10
Show Gist options
  • Save dom96/1511862 to your computer and use it in GitHub Desktop.
Save dom96/1511862 to your computer and use it in GitHub Desktop.
# Compile with --threads:on
import math, os, strutils, osproc, locks
type
TComplex = tuple[re, im: float]
TThrParam = tuple[start, size, realsize, id: int]
var bytes: array[0..3, cstring]
var lengths: array[0..3, int]
proc `+`(a, b: TComplex): TComplex =
return (a.re + b.re, a.im + b.im)
proc `*`(a, b: TComplex): TComplex =
result.re = a.re * b.re - a.im * b.im
result.im = a.re * b.im + a.im * b.re
proc abs2(a: TComplex): float =
return a.re * a.re + a.im * a.im
proc calc(arg: TThrParam) {.thread.} =
template ac(x: expr): stmt =
s[r] = x
r.inc()
var s: cstring = cast[cstring](allocShared0((arg.realSize - arg.start)*(arg.size+1)))
var r = 0
var bit = 128
var byteAcc = 0
var fsize = toFloat(arg.size)
var rfsize = toFloat(arg.realSize)
for y in arg.start .. arg.realsize-1:
var fy = 2.0 * toFloat(y) / fsize - 1.0
for x in 0 .. arg.size-1:
var z = (0.0, 0.0)
var c = (toFloat(2*x) / fsize - 1.5, fy)
block iter:
for i in 0 .. 49:
z = z*z + c
if abs2(z) >= 4.0:
break iter
byteAcc = byteAcc + bit
if bit > 1:
bit = bit div 2
else:
ac(chr(byteAcc))
bit = 128
byteAcc = 0
if bit != 128:
ac(chr(byteAcc))
bit = 128
byteAcc = 0
bytes[arg.id] = s
lengths[arg.id] = r
when isMainModule:
var size = parseInt(paramStr(1))
var realSize = size div 4
stdout.writeln("P4")
stdout.write($size)
stdout.write(" ")
stdout.writeln($size)
var threads: array[0..2, TThread[TThrParam]]
for i in 0..2:
var start = (realSize*i)
threads[i].createThread(calc, (start, size, realSize*(i+1), i))
calc(((realSize*3), size, realSize*4, 3))
joinThreads(threads)
for b in 0..3:
for x in 0..lengths[b]-1:
stdout.write(bytes[b][x])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment