<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog of developer Mikkel Ovesen &#187; thread</title>
	<atom:link href="http://blog.ovesens.net/tag/thread/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ovesens.net</link>
	<description>My thoughts, stuff I need to remember or things I just want to share with the world</description>
	<lastBuildDate>Thu, 27 May 2010 12:02:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Async Httphandlers in ASP.NET</title>
		<link>http://blog.ovesens.net/2010/05/async-httphandlers-in-asp-net/</link>
		<comments>http://blog.ovesens.net/2010/05/async-httphandlers-in-asp-net/#comments</comments>
		<pubDate>Thu, 27 May 2010 11:57:44 +0000</pubDate>
		<dc:creator>Mikkel Ovesen</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[httphandler]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://blog.ovesens.net/?p=235</guid>
		<description><![CDATA[What is the correct way to create a httphandler that potentially can take time and resources to complete.
Well this article explains it very well:
 http://msdn.microsoft.com/en-us/magazine/cc164128.aspx
If you don&#8217;t want to read all, you find the best solution in the bottom of the article.
But you can also find the code here, download this library C# Threadpool.
AsyncRequest
class AsyncRequest
{
  [...]]]></description>
			<content:encoded><![CDATA[<p>What is the correct way to create a httphandler that potentially can take time and resources to complete.</p>
<p>Well this article explains it very well:<br />
<a href="http://msdn.microsoft.com/en-us/magazine/cc164128.aspx" target="_blank"> http://msdn.microsoft.com/en-us/magazine/cc164128.aspx</a></p>
<p>If you don&#8217;t want to read all, you find the best solution in the bottom of the article.</p>
<p>But you can also find the code here, download this library <a href="http://blog.ovesens.net/wp-content/uploads/2010/05/threadpool.zip">C# Threadpool</a>.</p>
<h2>AsyncRequest</h2>
<pre id="ctl00_MTContentSelector1_mainContentContainer_ctl33_ctl00_ctl00_code">class AsyncRequest
{
  private AsyncRequestState _asyncRequestState;

  public AsyncRequest(AsyncRequestState ars)
  {
    _asyncRequestState = ars;
  }

  public void ProcessRequest()
  {
    // This is where the non-cpu-bound activity would take place, such as
    // accessing a Web Service, polling a slow piece of hardware, or
    // performing a lengthy database operation. I put the thread to sleep
    // for two seconds to simulate a lengthy operation.
    Thread.Sleep(2000);

    _asyncRequestState._ctx.Response.Output.Write(
            "AsyncThread, {0}",
            AppDomain.GetCurrentThreadId());

    // tell asp.net I am finished processing this request
    _asyncRequestState.CompleteRequest();
  }
}</pre>
<h2>AsyncHandler</h2>
<pre id="ctl00_MTContentSelector1_mainContentContainer_ctl35_ctl00_ctl00_code">namespace EssentialAspDotNet.HttpPipeline
{
  // AsyncRequestState and AsyncRequest remain the same
  // as in the previous example

  public class AsyncHandler : IHttpAsyncHandler
  {
    static DevelopMentor.ThreadPool _threadPool;

    static AsyncHandler()
    {
      _threadPool =
        new DevelopMentor.ThreadPool(2, 25, "AsyncPool");
      _threadPool.PropogateCallContext = true;
      _threadPool.PropogateThreadPrincipal = true;
      _threadPool.PropogateHttpContext = true;
      _threadPool.Start();
    }

    public void ProcessRequest(HttpContext ctx)
    {
     // not used
    }

    public bool IsReusable
    {
      get { return false;}
    }

    public IAsyncResult BeginProcessRequest(HttpContext ctx,
                     AsyncCallback cb, object obj)
    {
      AsyncRequestState reqState =
                     new AsyncRequestState(ctx, cb, obj);
      _threadPool.PostRequest(
                     new DevelopMentor.WorkRequestDelegate(ProcessRequest),
                     reqState);

      return reqState;
    }

    public void EndProcessRequest(IAsyncResult ar)
    {
    }

    void ProcessRequest(object state, DateTime requestTime)
    {
      AsyncRequestState reqState = state as AsyncRequestState;

      // Take some time to do it
      Thread.Sleep(2000);

      reqState._ctx.Response.Output.Write(
                   "AsyncThreadPool, {0}",
                    AppDomain.GetCurrentThreadId);

      // tell asp.net you are finished processing this request
      reqState.CompleteRequest();
    }

  }
}</pre>
<h2>AsyncPage</h2>
<pre>namespace EssentialAspDotNet.HttpPipeline
{
 public class AsyncPage : Page, IHttpAsyncHandler
  {
    static protected DevelopMentor.ThreadPool _threadPool;

    static AsyncPage()
    {
      _threadPool =
       new DevelopMentor.ThreadPool(2, 25, "AsyncPool");
      _threadPool.PropogateCallContext = true;
      _threadPool.PropogateThreadPrincipal = true;
      _threadPool.PropogateHttpContext = true;
      _threadPool.Start();
    }

    public new void ProcessRequest(HttpContext ctx)
    {
      // not used
    }

    public new bool IsReusable
    {
      get { return false;}
    }

    public IAsyncResult BeginProcessRequest(HttpContext ctx,
                                            AsyncCallback cb, object obj)
    {
      AsyncRequestState reqState =
             new AsyncRequestState(ctx, cb, obj);
      _threadPool.PostRequest(
             new DevelopMentor.WorkRequestDelegate(ProcessRequest),
             reqState);

      return reqState;
    }

    public void EndProcessRequest(IAsyncResult ar)
    {
    }

    void ProcessRequest(object state, DateTime requestTime)
    {
      AsyncRequestState reqState = state as AsyncRequestState;

      // Synchronously call base class Page.ProcessRequest
      // as you are now on a thread pool thread.
      base.ProcessRequest(reqState._ctx);

      // Once complete, call CompleteRequest to finish
      reqState.CompleteRequest();
    }
  }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.ovesens.net/2010/05/async-httphandlers-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How will you parallelize your existing codebase? Try R.A.S.P</title>
		<link>http://blog.ovesens.net/2008/12/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p/</link>
		<comments>http://blog.ovesens.net/2008/12/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p/#comments</comments>
		<pubDate>Wed, 24 Dec 2008 19:08:00 +0000</pubDate>
		<dc:creator>Mikkel Ovesen</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[thread]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">/post/2008/12/24/How-will-you-parallelize-your-existing-codebase-Try-RASP.aspx</guid>
		<description><![CDATA[
Original post:


http://www.atalasoft.com/cs/blogs/rickm/archive/2008/12/23/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p.aspx


&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-

How will you parallelize your existing codebase? Try R.A.S.P.

There
has been much talk of how we will be writing all of our new code with
parallelization in mind.&#160; However, what of our existing code?&#160; It&#8217;s
unlikely that everyone will just suddenly dump decades of existing code
and write everything from scratch.&#160; In this article I&#8217;m going to
provide a [...]]]></description>
			<content:encoded><![CDATA[<p>
Original post:
</p>
<p>
<a href="http://www.atalasoft.com/cs/blogs/rickm/archive/2008/12/23/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p.aspx">http://www.atalasoft.com/cs/blogs/rickm/archive/2008/12/23/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p.aspx</a>
</p>
<p>
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-
</p>
<h2>How will you parallelize your existing codebase? Try R.A.S.P.</h2>
<p>
There<br />
has been much talk of how we will be writing all of our new code with<br />
parallelization in mind.&nbsp; However, what of our existing code?&nbsp; It&rsquo;s<br />
unlikely that everyone will just suddenly dump decades of existing code<br />
and write everything from scratch.&nbsp; In this article I&rsquo;m going to<br />
provide a simple methodology for how we might deal with the ever<br />
building problem of parallelizing our existing mountains of code.&nbsp;<br />
Comments and contributions are welcome.
</p>
<p>
&nbsp;
</p>
<h3>Methodologies of the Past</h3>
<p>
From<br />
the STL to .NET, the frameworks we have constructed our applications<br />
around have been heavily dependent on the idea of an application having<br />
a single thread.&nbsp; Given that the foundation of what we have all been<br />
using for a very long time was constructed around this preconception,<br />
it&rsquo;s unreasonable to expect that much of our existing code will ever be<br />
fully parallel.&nbsp; Even those that wrote code on top of a thread safe<br />
framework may find that years of patches and and poor design decisions<br />
make ground up parallelization impossible.
</p>
<p>
If we set our<br />
expectations reasonably, we see that we should instead focus on<br />
leveraging parallelism to improve the performance of the slowest parts<br />
of our software.&nbsp; From this viewpoint, parallelization is an<br />
optimization problem.&nbsp; Like all optimization, the difficulty of<br />
parallelizing code will have much to do with the methodologies which<br />
were used to write it.&nbsp;&nbsp;
</p>
<p>
Of course, object-oriented code being written with modern <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">S.O.L.I.D. principles</a><br />
and will be easier to parallelize than older procedural code.&nbsp; At the<br />
same time, a poorly organized codebase or poorly written code will<br />
always make change difficult and so also hard to parallelize.&nbsp; This is<br />
why well written code is worth the investment.&nbsp; We will see the<br />
investment paying off in spades for the companies who have bothered to<br />
care about code quality.&nbsp; Others who find they have spaghetti code<br />
under the hood will find they will need to deeply segregate and<br />
modularize before parallelization is possible.
</p>
<p>
&nbsp;
</p>
<h3>A Methodology for Revisiting the Past</h3>
<p>
In<br />
most cases it would be a poor choice to implement your own threading<br />
API.&nbsp; Efficient and easy to use parallelization APIs are coming to (or<br />
already part of) every commonly used language and framework.&nbsp; Most of<br />
these APIs are not only built on top of <a href="http://lacl.univ-paris12.fr/gava/PAPP2009/">years of research</a>,<br />
they also have been written and debugged by a large number of people<br />
with specific expertise.&nbsp; These APIs are a godsend because they will<br />
allow most developers to parallelize existing software with a minimum<br />
amount of pain.&nbsp; The parallelization of existing code bases will be<br />
much the same as any other kind of performance tuning.&nbsp;
</p>
<p>
The<br />
key will be using a profiler to identify places in the code that would<br />
be sped up by parallelization and leveraging these new APIs to take<br />
advantage of the available hardware.&nbsp; The exciting part is that this<br />
can be done with any existing profiler and many existing APIs.&nbsp; The<br />
unfortunate part is that because memory sharing is such a big issue,<br />
parallelization requires a degree of separation beyond other types of<br />
optimization and so is likely to require some amount of refactoring.
</p>
<p>
Not<br />
all types of performance problems are conducive to being solved by<br />
parallelization, careful evaluation of the problem at hand is<br />
required.&nbsp; Also, as with anything that requires significant code<br />
change, building a solid test fixture is key to introducing as few bugs<br />
as possible.&nbsp; By leveraging the ideas of <a href="http://prematureoptimization.org/blog/archives/26">avoiding premature optimization</a>, <a href="http://dotnet.sys-con.com/node/133775">pragmatic unit testing</a>, <a href="http://msdn.microsoft.com/en-us/magazine/cc163329.aspx">using existing APIs</a>, and <a href="http://www.ryanlowe.ca/blog/archives/001048_be_mindful_of_code_entropy.php">mindful refactoring</a> it will be possible to introduce parallelization into many already existing projects with a manageable amount of risk.
</p>
<p>
&nbsp;
</p>
<h3>What is RASP?</h3>
<p>
While not included in the acronym, the first step in any kind of optimization is <strong><a href="http://en.wikipedia.org/wiki/Performance_analysis">profiling</a></strong>.&nbsp;<br />
Before you can begin to parallelize your code, you must determine where<br />
the bottlenecks might be.&nbsp; A broadly defined list of parallelizable<br />
things to look for would be, to quote <a href="http://loufranco.com/blog/files/20-Days-of-Clojure-Day-12.html">Rich Hickey</a>,<br />
&ldquo;independent data/work, moderate-to-course-grained work units and/or<br />
complex coordination logic that would be simplified with threads&rdquo;.&nbsp; A<br />
couple quick examples of low hanging fruit to be on the lookout for<br />
would be slow iterative loops and blocking I/O.&nbsp; It is important to<br />
note that as a general guideline it would be wrong to parallelize<br />
anything if it would not significantly increase the speed of your<br />
software.
</p>
<p>
For each of the bottlenecks found while profiling, parallelization is best separated into four steps:
</p>
<table border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td><strong>Review</strong>: </td>
<td>Review code to determine if it is a good candidate for parallelization.</td>
</tr>
<tr>
<td><strong>Anchor:</strong></td>
<td>Create a unit test fixture to ensure that the behavior of the to be parallelized code does not change.</td>
</tr>
<tr>
<td><strong>Separate</strong>: </td>
<td>Ensure that the to be parallelized code has no shared memory constraints, and if it does, factor them out if possible.</td>
</tr>
<tr>
<td><strong>Parallelize</strong>: </td>
<td>Minimally refactor for parallelization while leveraging an existing API to do the heavy lifting.</td>
</tr>
</tbody>
</table>
<p>
As<br />
the specifics of what each of these would entail depends greatly on<br />
exactly which platform and language is in use, I will not go into them<br />
deeply now.&nbsp; Overall, it&rsquo;s a simple methodology but I think both<br />
sufficient for the task at hand and broadly applicable.&nbsp;
</p>
<p>
&nbsp;
</p>
<h3>Conclusion </h3>
<p>
Review,<br />
Anchor, Separate, Parallelize.&nbsp; It&rsquo;s not intended to be a difficult<br />
concept but instead to provide a simple path to parallelization.&nbsp; I<br />
would be very interested in hearing about any opinions on what RASP<br />
might be missing or how it may be better clarified.&nbsp; While I didn&rsquo;t<br />
have time to discuss them deeply in this post, <a href="http://www.cs.uiuc.edu/homes/snir/PPP/">parallelization patterns</a><br />
are also a key concept in using RASP as if you can&rsquo;t easily identify<br />
what can be parallelized than it would be impossible to use any<br />
parallelization methodology.&nbsp; In the future I hope flush out RASP<br />
further as well as discuss parallelization patterns in depth.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ovesens.net/2008/12/how-will-you-parallelize-your-existing-codebase-try-r-a-s-p/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Jeff Richter Video on Asynchronous Programming and his Power Threading Library</title>
		<link>http://blog.ovesens.net/2008/12/jeff-richter-video-on-asynchronous-programming-and-his-power-threading-library/</link>
		<comments>http://blog.ovesens.net/2008/12/jeff-richter-video-on-asynchronous-programming-and-his-power-threading-library/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 17:26:00 +0000</pubDate>
		<dc:creator>Mikkel Ovesen</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[parallel]]></category>
		<category><![CDATA[plinq]]></category>
		<category><![CDATA[thread]]></category>

		<guid isPermaLink="false">/post/2008/12/10/Jeff-Richter-Video-on-Asynchronous-Programming-and-his-Power-Threading-Library.aspx</guid>
		<description><![CDATA[Jeff Richter Video on Asynchronous Programming and his Power Threading Library:

&#160;http://blogs.msdn.com/charlie/archive/2008/12/03/jeff-richter-video-on-asynchronous-programming-and-his-power-threading-library.aspx
]]></description>
			<content:encoded><![CDATA[<h1>Jeff Richter Video on Asynchronous Programming and his Power Threading Library:</h1>
<p>
&nbsp;<a href="http://blogs.msdn.com/charlie/archive/2008/12/03/jeff-richter-video-on-asynchronous-programming-and-his-power-threading-library.aspx">http://blogs.msdn.com/charlie/archive/2008/12/03/jeff-richter-video-on-asynchronous-programming-and-his-power-threading-library.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ovesens.net/2008/12/jeff-richter-video-on-asynchronous-programming-and-his-power-threading-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
