<div dir="ltr">The Control.Concurrent.bracket solution should involve Control.Concurrent.runInBoundThread as well.</div><div class="gmail_extra"><br><div class="gmail_quote">On 3 July 2018 at 11:10, Justin Paston-Cooper <span dir="ltr"><<a href="mailto:paston.cooper@gmail.com" target="_blank">paston.cooper@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div dir="ltr">glpk-hs defines a binding to glpk, a linear programme library. A linear programme is created by calling `glp_create_prob` and deleted by calling `glp_delete_prob`. These two C functions manage memory themselves using thread-local storage.<div><br></div><div>They are called by glpk-hs using the foreign function interface in the following code. Note that glpDelProb and glpCreateProb are imported foreign functions.</div><div><br></div><div><div><font face="monospace, monospace">runGLPK :: GLPK a -> IO a</font></div><div><font face="monospace, monospace">runGLPK m = do  lp <- newForeignPtr glpDelProb =<< glpCreateProb</font></div><div><font face="monospace, monospace">                withForeignPtr lp (execGLPK m)</font></div></div><div><font face="monospace, monospace"><br></font></div><div><font face="arial, helvetica, sans-serif">(<a href="https://github.com/jyp/glpk-hs/blob/master/src/Data/LinearProgram/GLPK/Types.hs" target="_blank">https://github.com/jyp/glpk-<wbr>hs/blob/master/src/Data/<wbr>LinearProgram/GLPK/Types.hs</a>)</font></div><div><font face="arial, helvetica, sans-serif"><br></font></div><div><font face="arial, helvetica, sans-serif">It seems that sometimes the finaliser is called in a thread different to the one where glp_create_prob is called. This leads to glpk aborting with a dynamic memory allocation error when tries to de-allocate the linear programme in the wrong thread-local storage, which has never seen that programme.</font></div><div><font face="arial, helvetica, sans-serif"><br></font></div><div><font face="arial, helvetica, sans-serif">Given that the ForeignPtr is used only in runGLPK, runGLPK could of course be fixed by using Control.Concurrent.bracket instead. However, I'm interested to know whether there is a solution to this problem.</font></div><div><font face="arial, helvetica, sans-serif"><br></font></div><div><font face="arial, helvetica, sans-serif">I'm only assuming that the finaliser sometimes runs in a different thread. If this is indeed the case, then is there any way to ensure that a finaliser runs in the thread where the pointer is created?</font></div></div>
</blockquote></div><br></div>