<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Kain64b's Blog</title>
	<atom:link href="http://kain64b.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://kain64b.wordpress.com</link>
	<description>Lazy Man's Blog</description>
	<lastBuildDate>Mon, 02 Jan 2012 12:32:29 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='kain64b.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Kain64b's Blog</title>
		<link>http://kain64b.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://kain64b.wordpress.com/osd.xml" title="Kain64b&#039;s Blog" />
	<atom:link rel='hub' href='http://kain64b.wordpress.com/?pushpress=hub'/>
		<item>
		<title>True &#8220;as is&#8221;</title>
		<link>http://kain64b.wordpress.com/2012/01/02/true-as-is/</link>
		<comments>http://kain64b.wordpress.com/2012/01/02/true-as-is/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 12:32:26 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=202</guid>
		<description><![CDATA[<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=202&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://kain64b.files.wordpress.com/2012/01/continuous-tax.png"><img src="http://kain64b.files.wordpress.com/2012/01/continuous-tax.png?w=300&#038;h=300" alt="" title="continuous-tax" width="300" height="300" class="alignnone size-medium wp-image-201" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/202/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/202/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/202/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=202&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2012/01/02/true-as-is/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>

		<media:content url="http://kain64b.files.wordpress.com/2012/01/continuous-tax.png?w=300" medium="image">
			<media:title type="html">continuous-tax</media:title>
		</media:content>
	</item>
		<item>
		<title>DOTPEEK WaU!</title>
		<link>http://kain64b.wordpress.com/2011/05/29/dotpeek-wau/</link>
		<comments>http://kain64b.wordpress.com/2011/05/29/dotpeek-wau/#comments</comments>
		<pubDate>Sun, 29 May 2011 19:19:21 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=192</guid>
		<description><![CDATA[BIG THANKS TO JET BRAINS!!! http://www.jetbrains.com/decompiler/index.html?topDP reflector-f..k off from my PC )<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=192&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>BIG THANKS TO JET BRAINS!!! http://www.jetbrains.com/decompiler/index.html?topDP<br />
reflector-f..k off from my PC )</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/192/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/192/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/192/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/192/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/192/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/192/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/192/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/192/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=192&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2011/05/29/dotpeek-wau/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>please share this!</title>
		<link>http://kain64b.wordpress.com/2011/05/22/please-share-this/</link>
		<comments>http://kain64b.wordpress.com/2011/05/22/please-share-this/#comments</comments>
		<pubDate>Sun, 22 May 2011 18:10:22 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=190</guid>
		<description><![CDATA[http://www.youtube.com/watch?v=k2hZ6SlSqq0&#38;annotation_id=annotation_97858&#38;feature=iv please share this and ask about this all friends<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=190&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>http://www.youtube.com/watch?v=k2hZ6SlSqq0&amp;annotation_id=annotation_97858&amp;feature=iv  please share this and ask about this all friends</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/190/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/190/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/190/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=190&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2011/05/22/please-share-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>Back to android</title>
		<link>http://kain64b.wordpress.com/2011/05/06/back-to-android/</link>
		<comments>http://kain64b.wordpress.com/2011/05/06/back-to-android/#comments</comments>
		<pubDate>Fri, 06 May 2011 20:51:34 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=186</guid>
		<description><![CDATA[Emulator runs very slow &#8211; pegs host&#8217;s CPU 100% (system_server using all the CPU) http://code.google.com/p/android/issues/detail?id=3099 wtf!? %)<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=186&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Emulator runs very slow &#8211; pegs host&#8217;s CPU 100% (system_server using all the CPU)<br />
http://code.google.com/p/android/issues/detail?id=3099 wtf!? %)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/186/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/186/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/186/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=186&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2011/05/06/back-to-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>The PiratBay</title>
		<link>http://kain64b.wordpress.com/2010/12/07/the-piratbay/</link>
		<comments>http://kain64b.wordpress.com/2010/12/07/the-piratbay/#comments</comments>
		<pubDate>Tue, 07 Dec 2010 20:02:32 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Lyric]]></category>
		<category><![CDATA[БлекДжек]]></category>
		<category><![CDATA[Интернет]]></category>
		<category><![CDATA[Шлюхи]]></category>
		<category><![CDATA[The PiratBay]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=182</guid>
		<description><![CDATA[‎&#8221;Пираты создадут собственный Интернет, потому что устали от цензуры в Сети&#8221;http://rus.newsru.ua/world/01dec2010/thepiratebay.html &#8220;ииихаа у нас будет свой интернет с блекджеком и шлюхами&#<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=182&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>‎&#8221;Пираты создадут собственный Интернет, потому что устали от цензуры в Сети&#8221;http://rus.newsru.ua/world/01dec2010/thepiratebay.html<br />
&#8220;ииихаа у нас будет свой интернет с блекджеком и шлюхами&#8221;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/182/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=182&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2010/12/07/the-piratbay/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>Unmanaged ThreadPool(c++)</title>
		<link>http://kain64b.wordpress.com/2010/11/28/unmanaged-threadpoolc/</link>
		<comments>http://kain64b.wordpress.com/2010/11/28/unmanaged-threadpoolc/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 22:53:28 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[pthreads]]></category>
		<category><![CDATA[Thread]]></category>
		<category><![CDATA[ThreadPool]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=169</guid>
		<description><![CDATA[And what about unmanaged thread pool For threading I will use pthreads lib(to make compatible code with all platforms that support POSIX standarts). First of all template synchronized queue( %) ): Same as C# implementation. And a simple ThreadPool : All simple but:friend void* ThreadFunc(void*); break all OOP no way to execute class function  <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=169&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>And what about unmanaged thread pool <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  For threading I will use <strong>pthreads</strong> lib(to make compatible code with all platforms that support POSIX standarts).<br />
First of all template synchronized queue(  %) ):<br />
<pre class="brush: csharp;">
#pragma once
#include&lt;queue&gt;
#include&quot;./pthreads/include/semaphore.h&quot;
#pragma comment(lib, &quot;./pthreads/lib/pthreadvc2.lib&quot;)

template &lt;class T&gt;
class BlockedQueue
{
private:
	sem_t _semaphore;
	std::queue&lt;T&gt; _queue;
public:
	T&amp; Dequeue();
	void Enqueue(T&amp;);
	BlockedQueue(void);
	~BlockedQueue(void);
};

template &lt;class T&gt;
BlockedQueue&lt;T&gt;::BlockedQueue(void)
{
	sem_init(&amp;_semaphore,0,-1);
}

template &lt;class T&gt;
BlockedQueue&lt;T&gt;::~BlockedQueue(void)
{
	sem_destroy(&amp;_semaphore);
}
template &lt;class T&gt;
void BlockedQueue&lt;T&gt;::Enqueue(T&amp; value){
	_queue.push(value);
	sem_post(&amp;_semaphore);
}
template &lt;class T&gt;
T&amp; BlockedQueue&lt;T&gt;::Dequeue(){
	sem_wait(&amp;_semaphore);
	T&amp; value = _queue.front();
	_queue.pop();
	return value;
}
 </pre><br />
Same as  C# implementation.<br />
And a simple ThreadPool :<br />
<pre class="brush: csharp;">
#pragma once
#include &quot;BlockedQueue.h&quot;
#include &quot;pthread.h&quot;
#include &lt;vector&gt;
typedef void (*Action)();

class ThreadsPool
{
private:
	std::vector&lt;pthread_t&gt; _threads;
	BlockedQueue&lt;Action&gt; _queue; 
	friend void* ThreadFunc(void*);
	void TaskExecutor();
	void StopAllThreads();
	
public:
	void QueueWorkItem(Action);
	ThreadsPool(int threadCount);
	~ThreadsPool(void);
};

#include &quot;ThreadsPool.h&quot;
#include &quot;pthread.h&quot;
#include &lt;stdexcept&gt;

void* ThreadFunc(void * state)
{
	try
	{
		ThreadsPool *poolRef = dynamic_cast&lt;ThreadsPool* &gt;((ThreadsPool*)state);
		if(!poolRef)
			return NULL;
		poolRef-&gt;TaskExecutor();
		return NULL;
	}
	catch(...){
		pthread_exit(NULL);
	throw;
	}
	pthread_exit(NULL);
	return NULL;
}
ThreadsPool::ThreadsPool(int threadsCount)
{
	if(threadsCount&lt;1)
		throw std::out_of_range(&quot;threadsCount&quot;);
	for (int i = 0;i&lt;threadsCount;i++)
	{
		pthread_t thread;
		int result= pthread_create(&amp;thread,NULL,ThreadFunc,this);
		if(result)
		{
			StopAllThreads();
			throw std::runtime_error(&quot;error creating thread&quot;);
		}
		_threads.push_back(thread);
	}
}
void ThreadsPool::StopAllThreads()
{
	for (std::vector&lt;pthread_t&gt;::const_iterator i=_threads.begin();i&lt;_threads.end();++i)
	{
		pthread_cancel(*i);
	}
}
ThreadsPool::~ThreadsPool(void)
{

}
void ThreadsPool::QueueWorkItem(Action action)
{
	_queue.Enqueue(action);
}
void ThreadsPool::TaskExecutor()
{
	while(1)
		try
		{
			_queue.Dequeue()();
		}
		catch (...)
		{
		}
		
}

 </pre><br />
All simple but:friend void* ThreadFunc(void*); break all OOP <img src='http://s0.wp.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  no way to execute class function <br />
And user code for  this library(I made smale dll with ThreadPool and 1 function:<br />
extern &#8220;C&#8221; {<br />
	MYDLL_API void QueueWorkItem(Action action);</p>
<p>}<br />
):<br />
For c++:<br />
<pre class="brush: csharp;">
// ThreadPoolTest.cpp : Defines the entry point for the console application.
//

#include &quot;stdafx.h&quot;
#include &quot;../ThreadPool/common.h&quot;
#include &lt;iostream&gt;
#include &lt;windows.h&gt;
#pragma comment(lib,&quot;../lib/threadpool.lib&quot;)
void f(){
	while(1){
		std::cout&lt;&lt;&quot;1111&quot;&lt;&lt;std::endl;
		Sleep(1000);
	}
}
void f1(){
	while(1)
	{	
		std::cout&lt;&lt;&quot;2222&quot;&lt;&lt;std::endl;
		Sleep(1500);
	}
}
void f2(){
	while(1)
	{
		std::cout&lt;&lt;&quot;3333&quot;&lt;&lt;std::endl;
		Sleep(2500);
	}
}
int _tmain(int argc, _TCHAR* argv[])

{
	QueueWorkItem(f);
	QueueWorkItem(f1);
	QueueWorkItem(f2);
	int i;
	std::cin&gt;&gt;i;
	return 0;
}
</pre><br />
And C# code:<br />
Prototype for export function from dll:<br />
        [DllImport(@"ThreadPool.dll")]<br />
        extern static void QueueWorkItem(Action action); </p>
<p><pre class="brush: csharp;">
using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace threadLibTestCS
{
    class Program
    {
        static void f()
        {
            while (true)
            {
                Console.WriteLine(&quot;1111&quot;);
                Thread.Sleep(1000);

            }
        }
        static void f1()
        {
            while (true)
            {
                Console.WriteLine(&quot;2222&quot;);
                Thread.Sleep(1500);

            }
        }
        static void f2()
        {
            while (true)
            {
                Console.WriteLine(&quot;3333&quot;);
                Thread.Sleep(2500);

            }
        }
        [DllImport(@&quot;ThreadPool.dll&quot;)]
        extern static void QueueWorkItem(Action action);
        static void Main(string[] args)
        {
            QueueWorkItem(f);
            QueueWorkItem(f1);
            QueueWorkItem(f2);
            Console.ReadLine();
        }
    }
}

</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/169/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=169&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2010/11/28/unmanaged-threadpoolc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>ManagedThreadPool</title>
		<link>http://kain64b.wordpress.com/2010/11/28/managedthreadpool/</link>
		<comments>http://kain64b.wordpress.com/2010/11/28/managedthreadpool/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 22:28:04 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C# 3.5]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[ThreadPool]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=162</guid>
		<description><![CDATA[In this post I try to implement fully managed Thread Pool. In previous post I implement Synchronized queue. Here I use this class with some modifications. All changes here: public T Dequeue() { _threadPool.SetThreadSleepState(Thread.CurrentThread,true); _semaphore.WaitOne(); lock (_tagRootSync) _threadPool.SetThreadSleepState(Thread.CurrentThread, false); …. For removing threads from pool we should know, that our thread sleep on our semaphore <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=162&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I try to implement fully managed Thread Pool. In previous post I implement Synchronized queue. Here I use this class with some modifications.<br />
<pre class="brush: csharp;">
using System.Collections.Generic;
using System.Threading;

namespace ManagedThreadPoolLib
{
    class SynchronyzedQueueForThreadPool&lt;T&gt;
    {
        private readonly ManagedThreadPool _threadPool;

        /// &lt;summary&gt;
        /// sync for internal queue
        /// &lt;/summary&gt;
        readonly object _rootSync = new object();
        /// &lt;summary&gt;
        /// sync for setting tag. used only by thread pool for killing sleeping threads 
        /// &lt;/summary&gt;
        readonly object _tagRootSync = new object();
        readonly Queue&lt;T&gt; _queue= new Queue&lt;T&gt;();
        readonly Semaphore _semaphore = new Semaphore(0,int.MaxValue);
        internal object TagRootSync
        {
            get { return _tagRootSync; }
        }

        public SynchronyzedQueueForThreadPool(ManagedThreadPool threadPool)
        {
            _threadPool = threadPool;
        }

        /// &lt;summary&gt;
        /// Enqueue element from queue and release semaphore
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;item&quot;&gt;&lt;/param&gt;
        public void Enqueue(T item)
        {
            lock (_rootSync)
            {
                _queue.Enqueue(item);  
            }
            _semaphore.Release();
        }
        /// &lt;summary&gt;
        /// Dequeue element to queue and WaitOne semaphore
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;item&quot;&gt;&lt;/param&gt;
        public T Dequeue()
        {
            _threadPool.SetThreadSleepState(Thread.CurrentThread,true);
            _semaphore.WaitOne();
            lock (_tagRootSync) _threadPool.SetThreadSleepState(Thread.CurrentThread, false);
            lock (_rootSync)
            {
                return _queue.Dequeue();
            }
        }
        /// &lt;summary&gt;
        /// clean Queue and invoke all sleep threads. Produce Exception if has sleeping threads in Dequeue operation
        /// &lt;/summary&gt;
        public void Clear()
        {
            lock (_rootSync)
            {
                int releaseCount = _queue.Count;
                _queue.Clear();
                _semaphore.Release(releaseCount);
            }
        }
    }
}

</pre><br />
All changes here:<br />
public T Dequeue()<br />
        {<br />
            _threadPool.SetThreadSleepState(Thread.CurrentThread,true);<br />
            _semaphore.WaitOne();<br />
            lock (_tagRootSync) _threadPool.SetThreadSleepState(Thread.CurrentThread, false);<br />
….<br />
For removing threads from pool we should know, that our thread sleep on our semaphore  or we can drop execution task with special synchronization.<br />
And here ManagedThreadPool Class:<br />
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;

namespace ManagedThreadPoolLib
{
    public class ManagedThreadPool
    {
        private readonly SynchronyzedQueueForThreadPool&lt;KeyValuePair&lt;WaitCallback, object&gt;&gt; _queueForThreadPool ;

        public ManagedThreadPool()
        {
            _queueForThreadPool = new SynchronyzedQueueForThreadPool&lt;KeyValuePair&lt;WaitCallback, object&gt;&gt;(this);
        }

        private bool _isStarted;
        private static int _threadIdCounter;
        private int _threadCount;
        private Dictionary&lt;Thread, bool&gt; _threadsAndStates = new Dictionary&lt;Thread, bool&gt;();
        /// &lt;summary&gt;
        /// Lister for exceptions in executed tasks
        /// &lt;/summary&gt;
        public event Action&lt;Exception&gt; OnExceptionInThread;
        private void InvokeOnExceptionInThread(Exception ex)
        {
            Action&lt;Exception&gt; handler = OnExceptionInThread;
            if (handler != null) handler(ex);
        }
        /// &lt;summary&gt;
        /// Run task from queue
        /// &lt;/summary&gt;
        private void ThreadFunc()
        {
            while (true)
            {
                try
                {
                    var pair=_queueForThreadPool.Dequeue();
                    pair.Key(pair.Value);
                }
                catch (Exception ex)
                {
                    InvokeOnExceptionInThread(ex);
                }
            }
        }

        private void SetThreadCount(int value)
        {
            lock (_threadsAndStates)
            {
                if (_threadsAndStates.Count &lt; value)
                {
                    AddThread(value - _threadsAndStates.Count);
                }
                else
                {
                    RemoveThreads();
                }
            }
        }

        private void RemoveThreads()
        {
            lock (_queueForThreadPool.TagRootSync)
            {
                Func&lt;Thread, bool&gt; predicate = thread =&gt; (thread.ThreadState &amp; ThreadState.WaitSleepJoin)
                                                           == ThreadState.WaitSleepJoin 
                                                           &amp;&amp;_threadsAndStates[thread];
                foreach (var thread in _threadsAndStates.Keys.Where(predicate).ToArray())
                {
                    try
                    {
                        thread.Abort();
                        _threadsAndStates.Remove(thread);
                    }
                    catch
                    {
                    }
                }
            }
        }

        private void AddThread(int value)
        {
            for (int i = 0; i &lt; value; i++)
            {
                var thread = new Thread(ThreadFunc);
                Interlocked.Increment(ref _threadIdCounter);
                thread.Name = string.Format(&quot;ManagedThreadPool:{0}&quot;, _threadIdCounter);
                thread.IsBackground = true;
                _threadsAndStates.Add(thread,false);
                thread.Start();
            }
        }

        /// &lt;summary&gt;
        /// set count of threads in thread pool
        /// &lt;/summary&gt;
        public int ThreadCount
        {
            get { return _threadCount; }
            set { SetThreadCount(value); }
        }
        public bool IsStarted { get { return _isStarted; } }
        /// &lt;summary&gt;
        /// Start ThreadPool
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;threadsCount&quot;&gt;&lt;/param&gt;
        public void Start(int threadsCount)
        {
            if (_isStarted)
                throw new InvalidOperationException(&quot;Already Started&quot;);
            _isStarted = true;
            AddThread(threadsCount);
        }

        /// &lt;summary&gt;
        /// Stop Thread pool executing
        /// &lt;/summary&gt;
        public void Stop()
        {
            if (!_isStarted)
                throw new InvalidOperationException(&quot;Not yet started&quot;);
            _isStarted = false;

            _threadsAndStates.Keys.ToList().ForEach(thread =&gt;
                                       {
                                           try
                                           {
                                               thread.Abort();
                                           }
                                           catch
                                           { }
                                       }
                                    );
            _threadsAndStates.Clear();
        }

        /// &lt;summary&gt;
        /// Add Task For Async Executing
        /// &lt;/summary&gt;
        public void AddWorkItem(WaitCallback action)
        {
            _queueForThreadPool.Enqueue(new KeyValuePair&lt;WaitCallback, object&gt;(action, null));
        }

        /// &lt;summary&gt;
        /// Add Task For Async Executing
        /// &lt;/summary&gt;
        public void AddWorkItem(WaitCallback action,object state)
        {
            _queueForThreadPool.Enqueue(new KeyValuePair&lt;WaitCallback, object&gt;(action, state));
        }
        public void AddWorkItem(Action action)
        {
            WaitCallback waitCallback = (state) =&gt; action();
            _queueForThreadPool.Enqueue(new KeyValuePair&lt;WaitCallback, object&gt;(waitCallback, null));
        }
        internal void SetThreadSleepState(Thread thread, bool state)
        {
            _threadsAndStates[thread] = state;
        }
    }
}

</pre><br />
And Small test code for thread pool<br />
<pre class="brush: csharp;">
using System;
using System.Threading;
using ManagedThreadPoolLib;

namespace ManagedThreadPoolTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagedThreadPool pool= new ManagedThreadPool();
            pool.Start(5);
            Random r = new Random();
            for (int i = 1; i &lt; 6; i++)
            {
                int counter = i;
                pool.AddWorkItem(() =&gt; {
                    while (true)
                    {
                        Console.WriteLine(counter.ToString());
                        return;
//                        Thread.Sleep(counter*1000);
                    }
                    
                                        }
                );    
            }
            pool.ThreadCount = 1;
            Thread.Sleep(5000);

            pool.AddWorkItem(() =&gt;
            {
                Random rnd = new Random((int)DateTime.Now.Ticks);
                while (true)
                {
                    Console.WriteLine(&quot;Q&quot;);
                    Thread.Sleep(rnd.Next(0,1000));
                }

            }
                );
            pool.AddWorkItem(() =&gt;
            {
                Random rnd = new Random((int) DateTime.Now.Ticks);
                while (true)
                {
                    Console.WriteLine(&quot;--------------------------&quot;);
                    Thread.Sleep(rnd.Next(0,250));
                }

            }
                );
            pool.AddWorkItem(() =&gt;
            {
                Random rnd = new Random((int)DateTime.Now.Ticks);
                while (true)
                {
                    Console.WriteLine(&quot;W&quot;);
                    Thread.Sleep(rnd.Next(0,500));
                }

            }
                );
            Console.WriteLine(&quot;--------------------------------------------&quot;);
            Console.WriteLine(&quot;--------------------------------------------&quot;);
            pool.ThreadCount = 5;
            Console.ReadLine();
            pool.Stop();
        }
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/162/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/162/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/162/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=162&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2010/11/28/managedthreadpool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>SynchronizedQueue or readers-writers synchronization</title>
		<link>http://kain64b.wordpress.com/2010/11/13/synchronizedqueue-or-readers-writers-synchronization/</link>
		<comments>http://kain64b.wordpress.com/2010/11/13/synchronizedqueue-or-readers-writers-synchronization/#comments</comments>
		<pubDate>Sat, 13 Nov 2010 17:36:05 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C# 3.5]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[synchronization]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=158</guid>
		<description><![CDATA[1)writers can put something in queue 2)reader can take something from queue 3) if queue is empty readers wait while writers put something in queue<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=158&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>1)writers can put something in queue<br />
2)reader can take  something from queue<br />
3) if queue is empty readers wait while writers put something in queue <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
<pre class="brush: csharp;">
public class SynchronyzedQueue&lt;T&gt;
    {
        readonly object _rootSync = new object();//sync internal queue 
        readonly Queue&lt;T&gt; _queue= new Queue&lt;T&gt;();//internal queue 
        readonly Semaphore _semaphore = new Semaphore(0,int.MaxValue);
       
        /// &lt;summary&gt;
        /// Enqueue element from queue and release semaphore
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;item&quot;&gt;&lt;/param&gt;
        public void Enqueue(T item)
        {
            lock (_rootSync)
            {
                _queue.Enqueue(item);  
            }
            _semaphore.Release();
        }
        /// &lt;summary&gt;
        /// Dequeue element to queue and WaitOne semaphore
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;item&quot;&gt;&lt;/param&gt;
        public T Dequeue()
        {
            _semaphore.WaitOne();
            lock (_rootSync)
            {
                return _queue.Dequeue();
            }
        }
        /// &lt;summary&gt;
        /// clean Queue and invoke all sleep threads. Produce Exception if has sleeping threads in Dequeue operation
        /// &lt;/summary&gt;
        public void Clear()
        {
            lock (_rootSync)
            {
                int releaseCount = _queue.Count;
                _queue.Clear();
                _semaphore.Release(releaseCount);
            }
        }
    }
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/158/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/158/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/158/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=158&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2010/11/13/synchronizedqueue-or-readers-writers-synchronization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>
	</item>
		<item>
		<title>Unit of Work pattern and  nhibernate or another bicycle building :)</title>
		<link>http://kain64b.wordpress.com/2010/10/01/unit-of-work-pattern-and-nhibernate-or-another-bicycle-building/</link>
		<comments>http://kain64b.wordpress.com/2010/10/01/unit-of-work-pattern-and-nhibernate-or-another-bicycle-building/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 18:51:05 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[Unit of work]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=150</guid>
		<description><![CDATA[I share old bicycle today maybe it&#8217;s will be useful for somebody. Theory always first: When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database. Similarly you have to insert new objects you create and remove <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=150&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I share old bicycle today <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  maybe it&#8217;s will be useful for somebody.<br />
Theory always first:<br />
<code><br />
<img src="http://martinfowler.com/eaaCatalog/unitOfWorkInterface.gif" alt="unit of work" /><br />
When you're pulling data in and out of a database, it's important to keep track of what you've changed; otherwise, that data won't be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete.</p>
<p>You can change the database with each change to your object model, but this can lead to lots of very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads.</p>
<p>A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.</code><br />
<a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">http://martinfowler.com/eaaCatalog/unitOfWork.html</a><br />
First of all  describe base class for Entity classes:<br />
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Domain
{
    public class Entity
    {
        private int _id;
        public virtual int Id
        {
            get { return _id; }
            set { _id = value; }
        }
        
        public static bool operator ==(Entity first, Entity second)
        {
            if (object.ReferenceEquals(first, null) &amp;&amp; object.ReferenceEquals(second, null))
                return true;
            if (object.ReferenceEquals(first, null) || object.ReferenceEquals(second, null))
                return false;
            return first.Equals(second);
        }

        public static bool operator !=(Entity first, Entity second)
        {
            return !(first == second);
        }

        public override bool Equals(object obj)
        {
            if (base.Equals(obj))
                return true;
            if (obj is Entity)
                return ((Entity)obj).Id == Id &amp;&amp; obj.GetType() == GetType();
            return false;
        }

        public override int GetHashCode()
        {
            return Id ^ GetType().GetHashCode();
        }
    }
}
</pre></p>
<p>And work unit class code:<br />
<pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using NHibernate;

namespace Domain
{
    public class EntityWorkUnit : IDisposable
    {
        private readonly List&lt;Entity&gt; _added = new List&lt;Entity&gt;();
        private readonly List&lt;Entity&gt; _dirty = new List&lt;Entity&gt;();
        private readonly List&lt;Entity&gt; _deleted = new List&lt;Entity&gt;();
        private readonly HibernateHelper _hibernateHelper;
        private bool _disposed;
        private static int _dummyId;

        public static int DummyId
        {
            get
            {
                _dummyId--;
                return _dummyId;
            }
            private set { _dummyId = value; }
        }

        public EntityWorkUnit()
        {
            _hibernateHelper = new HibernateHelper();
        }

        public ISession CurrentSession
        {
            get
            {
                return _hibernateHelper.CurrentSession;
            }
        }
        private void checkIsNotNull(Entity entity)
        {
            if (entity == null)
                throw new NullReferenceException(&quot;entity is null&quot;);
        }
        public void AddNewEntity(Entity entity)
        {
            checkIsNotNull(entity);
            if (_added.Contains(entity))
                throw new ApplicationException(&quot;entity already in added list&quot;);
            _added.Add(entity);
        }

        public void SaveAll()
        {
            lock (_hibernateHelper.CurrentSession)
            {
                ISession currentSession = _hibernateHelper.CurrentSession;
                using (ITransaction transaction = currentSession.BeginTransaction())
                {
                    foreach (Entity entity in _added)
                        currentSession.Save(entity);
                    foreach (Entity entity in _dirty)
                        currentSession.SaveOrUpdate(entity);
                    foreach (Entity entity in _deleted)
                        currentSession.Delete(entity);
                    _added.Clear();
                    _dirty.Clear();
                    _deleted.Clear();
                    transaction.Commit();
                    currentSession.Flush();
                }
                DummyId = 0;
            }
        }

        public void AddDirtyEntity(Entity entity)
        {
            checkIsNotNull(entity);
            if (_dirty.Contains(entity))
                throw new ApplicationException(&quot;entity already in dirty list&quot;);
            _dirty.Add(entity);
        }

        public void AddDeletedEntity(Entity entity)
        {
            checkIsNotNull(entity);
            if (_deleted.Contains(entity))
                throw new ApplicationException(&quot;entity already in deleted list&quot;);
            _deleted.Add(entity);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                _disposed = true;
                if (disposing) 
                    _hibernateHelper.Dispose();
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~EntityWorkUnit()
        {
            Dispose(false);
        }
    }
}
</pre></p>
<p>And last one Hibernate Helper:<br />
<pre class="brush: csharp;">
using System;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using NHibernate;
using NHibernate.Cfg;

namespace Domain
{
    internal class HibernateHelper:IDisposable
    {
        private ISessionFactory _sessionFactory;
        public HibernateHelper()
        {
            Init();
        }

        public  ISession CurrentSession{
            get; private set;
        }
        /// &lt;summary&gt;
        /// create hibernate config by template
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static string CreateHibernateConfig()
        {
            const string connectionconfigXml = @&quot;.\connectionconfig.xml&quot;;
            if (!File.Exists(connectionconfigXml))
                throw new ApplicationException(&quot;No Config File&quot;);
            XElement configFile = XElement.Load(connectionconfigXml);
            var config=configFile.Descendants().First();
            if(config == null)
                throw new ApplicationException(&quot;Config File bad format&quot;);

            XElement hibernateConfigs = XElement.Parse(HibernateConfigs.HibernateDialects);
            var dbTypeAttribute = config.Attribute(&quot;Type&quot;);
            if (dbTypeAttribute == null)
                throw new ApplicationException(&quot;Config File bad format. Type attribute not found&quot;);
            
            string dbConnectionType = dbTypeAttribute.Value;
            if (string.IsNullOrEmpty(dbConnectionType))
                throw new ApplicationException(&quot;Config File bad format. Type is empty&quot;);

            var connectionStringAttribute = config.Attribute(&quot;ConnectionString&quot;);
            if (connectionStringAttribute == null)
                throw new ApplicationException(&quot;Config File bad format. Connection String attribute not found&quot;);

            var connectionString = connectionStringAttribute.Value;
            if (string.IsNullOrEmpty(connectionString))
                throw new ApplicationException(&quot;Config File bad format. Connection string is empty&quot;);

            var options= hibernateConfigs.Descendants().FirstOrDefault(
                element =&gt; element.Attribute(&quot;Type&quot;).Value == dbConnectionType);
            if (options == null)
                throw new ApplicationException(string.Format(&quot;Wrong DB Connection Type:{0}&quot;, dbConnectionType));
            
            return string.Format(HibernateConfigs.HibernateConfigTemplate,options.Attribute(&quot;Driver&quot;).Value,connectionString,options.Attribute(&quot;Dialect&quot;).Value);
        }
        private  void Init()
        {
            Configuration configuration;
            using (var memstream = new MemoryStream())
            {
                using (var sw = new StreamWriter(memstream))
                {
                    sw.Write(CreateHibernateConfig());
                    sw.Flush();
                    memstream.Flush();
                    memstream.Seek(0, SeekOrigin.Begin);
                    using (XmlReader xreader = XmlReader.Create(memstream))
                    {
                        configuration = new Configuration().Configure(xreader);
                    }
                }
            }
            DomainXmlHelper.Load(configuration);//configuration.AddXml(&quot;&lt;?xml&gt;...
            _sessionFactory = configuration.BuildSessionFactory();
            CurrentSession = _sessionFactory.OpenSession();
        }

        private void Close()
        {
        
            if (CurrentSession != null)
            {
                CurrentSession.Close();
            }
        }

        #region IDisposable

        private bool _disposed;
        public void Dispose()
        {
            Dispose(true);
        }
        private void Dispose(bool disposing)
        {
            if (disposing &amp;&amp; !_disposed)
            {
                Close();
                GC.SuppressFinalize(this);
            }
            _disposed = true;
        }
        ~HibernateHelper()
        {
            Dispose(false);
        }

        #endregion

    }
}
</pre><br />
How to use if?<br />
Example:<br />
<pre class="brush: csharp;">
class Person:Entity
{...}
//Do not forget map in HBM file to nhibernate Person class.
EntityWorkUnit entityWorkUnit = new EntityWorkUnit();
Person newperson = new Person();
entityWorkUnit.AddNewEntity(newperson);
Person existingPerson = GetPersonById(PERSON_ID);
existingPerson.Data_Field = NEW_VALUE;
entityWorkUnit.AddDirtyEntity(newperson);
Person deletePerson = GetPersonById(PERSON_ID_FOR_DELETE);
entityWorkUnit.AddDeletedEntity(deletePerson);
EntityWorkUnit.Instance.SaveAll();
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/150/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/150/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/150/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=150&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2010/10/01/unit-of-work-pattern-and-nhibernate-or-another-bicycle-building/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>

		<media:content url="http://martinfowler.com/eaaCatalog/unitOfWorkInterface.gif" medium="image">
			<media:title type="html">unit of work</media:title>
		</media:content>
	</item>
		<item>
		<title>Lyric</title>
		<link>http://kain64b.wordpress.com/2010/08/22/lyric/</link>
		<comments>http://kain64b.wordpress.com/2010/08/22/lyric/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 17:01:32 +0000</pubDate>
		<dc:creator>kain64b</dc:creator>
				<category><![CDATA[Lyric]]></category>

		<guid isPermaLink="false">http://kain64b.wordpress.com/?p=145</guid>
		<description><![CDATA[<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=145&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://kain64b.files.wordpress.com/2010/08/dsc00463.jpg"><img src="http://kain64b.files.wordpress.com/2010/08/dsc00463.jpg?w=300&#038;h=225" alt="" title="Tel aviv beach" width="300" height="225" class="alignnone size-medium wp-image-146" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/kain64b.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/kain64b.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/kain64b.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/kain64b.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/kain64b.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/kain64b.wordpress.com/145/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/kain64b.wordpress.com/145/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/kain64b.wordpress.com/145/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=kain64b.wordpress.com&amp;blog=5737445&amp;post=145&amp;subd=kain64b&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://kain64b.wordpress.com/2010/08/22/lyric/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/74d1d37e317b4bd7bf5d8ca259a101dc?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kain64b</media:title>
		</media:content>

		<media:content url="http://kain64b.files.wordpress.com/2010/08/dsc00463.jpg?w=300" medium="image">
			<media:title type="html">Tel aviv beach</media:title>
		</media:content>
	</item>
	</channel>
</rss>
