Created
December 18, 2016 19:48
-
-
Save singularperturbation/6456395e84718bade7edd98e62ba148f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Example of using linalg library with ref-counting GC. If *just* have ptr DMatrix64, then | |
## it will get GC'd since the DMatrix64 is a ref to an object - the GC doesn't keep track of ptrs (duh) | |
## so this will be collected on the next cycle. | |
## | |
## Solution is as the example in the manual for the string in the 'Data' tuple. Ideal solution would be | |
## automatically-managed memory container with destructor that deallocates the matrix, but the Matrix | |
## definition might have to be managed to support that. | |
import linalg | |
import threadpool | |
type ThreadSafeMatrixContainer = object | |
matrix: DMatrix64 | |
var resultMatrix : ptr ThreadSafeMatrixContainer | |
proc createThreadSafeMatrixContainer(rows, cols: int): ptr ThreadSafeMatrixContainer = | |
result = createShared(ThreadSafeMatrixContainer) | |
result.matrix = zeros(rows, cols) | |
GC_ref(result.matrix) | |
proc calcMatrixSlice(chunk: Slice[int]) = | |
for i in chunk: | |
let v = randomVector(500) | |
for j in 0 .. <500: | |
resultMatrix[].matrix[i, j] = v[j] | |
proc main() = | |
let NUM_CHUNKS = 3 | |
let (nrow, ncol) = (300, 500) | |
resultMatrix = createThreadSafeMatrixContainer(nrow, ncol) | |
echo repr(resultMatrix) | |
echo repr(resultMatrix[]) | |
echo resultMatrix[] | |
for i in 0 .. <NUM_CHUNKS: | |
let starting = 100 * i | |
let ending = (100 * (i + 1)) - 1 | |
spawn calcMatrixSlice(starting .. ending) | |
GC_fullCollect() | |
sync() | |
echo isNil(resultMatrix) | |
echo repr(resultMatrix) | |
echo "Result Matrix: \n" & $resultMatrix[] | |
GC_unref(resultMatrix.matrix) | |
deallocShared(resultMatrix) | |
when isMainModule: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment