True “as is”

DOTPEEK WaU!

BIG THANKS TO JET BRAINS!!! http://www.jetbrains.com/decompiler/index.html?topDP
reflector-f..k off from my PC )

please share this!

http://www.youtube.com/watch?v=k2hZ6SlSqq0&annotation_id=annotation_97858&feature=iv please share this and ask about this all friends

Back to android

Emulator runs very slow – pegs host’s CPU 100% (system_server using all the CPU)
http://code.google.com/p/android/issues/detail?id=3099 wtf!? %)

The PiratBay

‎”Пираты создадут собственный Интернет, потому что устали от цензуры в Сети”http://rus.newsru.ua/world/01dec2010/thepiratebay.html
“ииихаа у нас будет свой интернет с блекджеком и шлюхами”

Unmanaged ThreadPool(c++)

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( %) ):

#pragma once
#include<queue>
#include"./pthreads/include/semaphore.h"
#pragma comment(lib, "./pthreads/lib/pthreadvc2.lib")

template <class T>
class BlockedQueue
{
private:
	sem_t _semaphore;
	std::queue<T> _queue;
public:
	T& Dequeue();
	void Enqueue(T&);
	BlockedQueue(void);
	~BlockedQueue(void);
};

template <class T>
BlockedQueue<T>::BlockedQueue(void)
{
	sem_init(&_semaphore,0,-1);
}

template <class T>
BlockedQueue<T>::~BlockedQueue(void)
{
	sem_destroy(&_semaphore);
}
template <class T>
void BlockedQueue<T>::Enqueue(T& value){
	_queue.push(value);
	sem_post(&_semaphore);
}
template <class T>
T& BlockedQueue<T>::Dequeue(){
	sem_wait(&_semaphore);
	T& value = _queue.front();
	_queue.pop();
	return value;
}
 

Same as C# implementation.
And a simple ThreadPool :
#pragma once
#include "BlockedQueue.h"
#include "pthread.h"
#include <vector>
typedef void (*Action)();

class ThreadsPool
{
private:
	std::vector<pthread_t> _threads;
	BlockedQueue<Action> _queue; 
	friend void* ThreadFunc(void*);
	void TaskExecutor();
	void StopAllThreads();
	
public:
	void QueueWorkItem(Action);
	ThreadsPool(int threadCount);
	~ThreadsPool(void);
};

#include "ThreadsPool.h"
#include "pthread.h"
#include <stdexcept>

void* ThreadFunc(void * state)
{
	try
	{
		ThreadsPool *poolRef = dynamic_cast<ThreadsPool* >((ThreadsPool*)state);
		if(!poolRef)
			return NULL;
		poolRef->TaskExecutor();
		return NULL;
	}
	catch(...){
		pthread_exit(NULL);
	throw;
	}
	pthread_exit(NULL);
	return NULL;
}
ThreadsPool::ThreadsPool(int threadsCount)
{
	if(threadsCount<1)
		throw std::out_of_range("threadsCount");
	for (int i = 0;i<threadsCount;i++)
	{
		pthread_t thread;
		int result= pthread_create(&thread,NULL,ThreadFunc,this);
		if(result)
		{
			StopAllThreads();
			throw std::runtime_error("error creating thread");
		}
		_threads.push_back(thread);
	}
}
void ThreadsPool::StopAllThreads()
{
	for (std::vector<pthread_t>::const_iterator i=_threads.begin();i<_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 (...)
		{
		}
		
}

 

All simple but:friend void* ThreadFunc(void*); break all OOP :( no way to execute class function 
And user code for this library(I made smale dll with ThreadPool and 1 function:
extern “C” {
MYDLL_API void QueueWorkItem(Action action);

}
):
For c++:

// ThreadPoolTest.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "../ThreadPool/common.h"
#include <iostream>
#include <windows.h>
#pragma comment(lib,"../lib/threadpool.lib")
void f(){
	while(1){
		std::cout<<"1111"<<std::endl;
		Sleep(1000);
	}
}
void f1(){
	while(1)
	{	
		std::cout<<"2222"<<std::endl;
		Sleep(1500);
	}
}
void f2(){
	while(1)
	{
		std::cout<<"3333"<<std::endl;
		Sleep(2500);
	}
}
int _tmain(int argc, _TCHAR* argv[])

{
	QueueWorkItem(f);
	QueueWorkItem(f1);
	QueueWorkItem(f2);
	int i;
	std::cin>>i;
	return 0;
}

And C# code:
Prototype for export function from dll:
[DllImport(@"ThreadPool.dll")]
extern static void QueueWorkItem(Action action);

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace threadLibTestCS
{
    class Program
    {
        static void f()
        {
            while (true)
            {
                Console.WriteLine("1111");
                Thread.Sleep(1000);

            }
        }
        static void f1()
        {
            while (true)
            {
                Console.WriteLine("2222");
                Thread.Sleep(1500);

            }
        }
        static void f2()
        {
            while (true)
            {
                Console.WriteLine("3333");
                Thread.Sleep(2500);

            }
        }
        [DllImport(@"ThreadPool.dll")]
        extern static void QueueWorkItem(Action action);
        static void Main(string[] args)
        {
            QueueWorkItem(f);
            QueueWorkItem(f1);
            QueueWorkItem(f2);
            Console.ReadLine();
        }
    }
}

ManagedThreadPool

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.

using System.Collections.Generic;
using System.Threading;

namespace ManagedThreadPoolLib
{
    class SynchronyzedQueueForThreadPool<T>
    {
        private readonly ManagedThreadPool _threadPool;

        /// <summary>
        /// sync for internal queue
        /// </summary>
        readonly object _rootSync = new object();
        /// <summary>
        /// sync for setting tag. used only by thread pool for killing sleeping threads 
        /// </summary>
        readonly object _tagRootSync = new object();
        readonly Queue<T> _queue= new Queue<T>();
        readonly Semaphore _semaphore = new Semaphore(0,int.MaxValue);
        internal object TagRootSync
        {
            get { return _tagRootSync; }
        }

        public SynchronyzedQueueForThreadPool(ManagedThreadPool threadPool)
        {
            _threadPool = threadPool;
        }

        /// <summary>
        /// Enqueue element from queue and release semaphore
        /// </summary>
        /// <param name="item"></param>
        public void Enqueue(T item)
        {
            lock (_rootSync)
            {
                _queue.Enqueue(item);  
            }
            _semaphore.Release();
        }
        /// <summary>
        /// Dequeue element to queue and WaitOne semaphore
        /// </summary>
        /// <param name="item"></param>
        public T Dequeue()
        {
            _threadPool.SetThreadSleepState(Thread.CurrentThread,true);
            _semaphore.WaitOne();
            lock (_tagRootSync) _threadPool.SetThreadSleepState(Thread.CurrentThread, false);
            lock (_rootSync)
            {
                return _queue.Dequeue();
            }
        }
        /// <summary>
        /// clean Queue and invoke all sleep threads. Produce Exception if has sleeping threads in Dequeue operation
        /// </summary>
        public void Clear()
        {
            lock (_rootSync)
            {
                int releaseCount = _queue.Count;
                _queue.Clear();
                _semaphore.Release(releaseCount);
            }
        }
    }
}


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  or we can drop execution task with special synchronization.
And here ManagedThreadPool Class:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;

namespace ManagedThreadPoolLib
{
    public class ManagedThreadPool
    {
        private readonly SynchronyzedQueueForThreadPool<KeyValuePair<WaitCallback, object>> _queueForThreadPool ;

        public ManagedThreadPool()
        {
            _queueForThreadPool = new SynchronyzedQueueForThreadPool<KeyValuePair<WaitCallback, object>>(this);
        }

        private bool _isStarted;
        private static int _threadIdCounter;
        private int _threadCount;
        private Dictionary<Thread, bool> _threadsAndStates = new Dictionary<Thread, bool>();
        /// <summary>
        /// Lister for exceptions in executed tasks
        /// </summary>
        public event Action<Exception> OnExceptionInThread;
        private void InvokeOnExceptionInThread(Exception ex)
        {
            Action<Exception> handler = OnExceptionInThread;
            if (handler != null) handler(ex);
        }
        /// <summary>
        /// Run task from queue
        /// </summary>
        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 < value)
                {
                    AddThread(value - _threadsAndStates.Count);
                }
                else
                {
                    RemoveThreads();
                }
            }
        }

        private void RemoveThreads()
        {
            lock (_queueForThreadPool.TagRootSync)
            {
                Func<Thread, bool> predicate = thread => (thread.ThreadState & ThreadState.WaitSleepJoin)
                                                           == ThreadState.WaitSleepJoin 
                                                           &&_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 < value; i++)
            {
                var thread = new Thread(ThreadFunc);
                Interlocked.Increment(ref _threadIdCounter);
                thread.Name = string.Format("ManagedThreadPool:{0}", _threadIdCounter);
                thread.IsBackground = true;
                _threadsAndStates.Add(thread,false);
                thread.Start();
            }
        }

        /// <summary>
        /// set count of threads in thread pool
        /// </summary>
        public int ThreadCount
        {
            get { return _threadCount; }
            set { SetThreadCount(value); }
        }
        public bool IsStarted { get { return _isStarted; } }
        /// <summary>
        /// Start ThreadPool
        /// </summary>
        /// <param name="threadsCount"></param>
        public void Start(int threadsCount)
        {
            if (_isStarted)
                throw new InvalidOperationException("Already Started");
            _isStarted = true;
            AddThread(threadsCount);
        }

        /// <summary>
        /// Stop Thread pool executing
        /// </summary>
        public void Stop()
        {
            if (!_isStarted)
                throw new InvalidOperationException("Not yet started");
            _isStarted = false;

            _threadsAndStates.Keys.ToList().ForEach(thread =>
                                       {
                                           try
                                           {
                                               thread.Abort();
                                           }
                                           catch
                                           { }
                                       }
                                    );
            _threadsAndStates.Clear();
        }

        /// <summary>
        /// Add Task For Async Executing
        /// </summary>
        public void AddWorkItem(WaitCallback action)
        {
            _queueForThreadPool.Enqueue(new KeyValuePair<WaitCallback, object>(action, null));
        }

        /// <summary>
        /// Add Task For Async Executing
        /// </summary>
        public void AddWorkItem(WaitCallback action,object state)
        {
            _queueForThreadPool.Enqueue(new KeyValuePair<WaitCallback, object>(action, state));
        }
        public void AddWorkItem(Action action)
        {
            WaitCallback waitCallback = (state) => action();
            _queueForThreadPool.Enqueue(new KeyValuePair<WaitCallback, object>(waitCallback, null));
        }
        internal void SetThreadSleepState(Thread thread, bool state)
        {
            _threadsAndStates[thread] = state;
        }
    }
}


And Small test code for thread pool
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 < 6; i++)
            {
                int counter = i;
                pool.AddWorkItem(() => {
                    while (true)
                    {
                        Console.WriteLine(counter.ToString());
                        return;
//                        Thread.Sleep(counter*1000);
                    }
                    
                                        }
                );    
            }
            pool.ThreadCount = 1;
            Thread.Sleep(5000);

            pool.AddWorkItem(() =>
            {
                Random rnd = new Random((int)DateTime.Now.Ticks);
                while (true)
                {
                    Console.WriteLine("Q");
                    Thread.Sleep(rnd.Next(0,1000));
                }

            }
                );
            pool.AddWorkItem(() =>
            {
                Random rnd = new Random((int) DateTime.Now.Ticks);
                while (true)
                {
                    Console.WriteLine("--------------------------");
                    Thread.Sleep(rnd.Next(0,250));
                }

            }
                );
            pool.AddWorkItem(() =>
            {
                Random rnd = new Random((int)DateTime.Now.Ticks);
                while (true)
                {
                    Console.WriteLine("W");
                    Thread.Sleep(rnd.Next(0,500));
                }

            }
                );
            Console.WriteLine("--------------------------------------------");
            Console.WriteLine("--------------------------------------------");
            pool.ThreadCount = 5;
            Console.ReadLine();
            pool.Stop();
        }
    }
}

SynchronizedQueue or readers-writers synchronization

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 :)

public class SynchronyzedQueue<T>
    {
        readonly object _rootSync = new object();//sync internal queue 
        readonly Queue<T> _queue= new Queue<T>();//internal queue 
        readonly Semaphore _semaphore = new Semaphore(0,int.MaxValue);
       
        /// <summary>
        /// Enqueue element from queue and release semaphore
        /// </summary>
        /// <param name="item"></param>
        public void Enqueue(T item)
        {
            lock (_rootSync)
            {
                _queue.Enqueue(item);  
            }
            _semaphore.Release();
        }
        /// <summary>
        /// Dequeue element to queue and WaitOne semaphore
        /// </summary>
        /// <param name="item"></param>
        public T Dequeue()
        {
            _semaphore.WaitOne();
            lock (_rootSync)
            {
                return _queue.Dequeue();
            }
        }
        /// <summary>
        /// clean Queue and invoke all sleep threads. Produce Exception if has sleeping threads in Dequeue operation
        /// </summary>
        public void Clear()
        {
            lock (_rootSync)
            {
                int releaseCount = _queue.Count;
                _queue.Clear();
                _semaphore.Release(releaseCount);
            }
        }
    }

Unit of Work pattern and nhibernate or another bicycle building :)

I share old bicycle today :) maybe it’s will be useful for somebody.
Theory always first:

unit of work
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.

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.

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.
http://martinfowler.com/eaaCatalog/unitOfWork.html
First of all describe base class for Entity classes:

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) && 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 && obj.GetType() == GetType();
            return false;
        }

        public override int GetHashCode()
        {
            return Id ^ GetType().GetHashCode();
        }
    }
}

And work unit class code:

using System;
using System.Collections.Generic;
using NHibernate;

namespace Domain
{
    public class EntityWorkUnit : IDisposable
    {
        private readonly List<Entity> _added = new List<Entity>();
        private readonly List<Entity> _dirty = new List<Entity>();
        private readonly List<Entity> _deleted = new List<Entity>();
        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("entity is null");
        }
        public void AddNewEntity(Entity entity)
        {
            checkIsNotNull(entity);
            if (_added.Contains(entity))
                throw new ApplicationException("entity already in added list");
            _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("entity already in dirty list");
            _dirty.Add(entity);
        }

        public void AddDeletedEntity(Entity entity)
        {
            checkIsNotNull(entity);
            if (_deleted.Contains(entity))
                throw new ApplicationException("entity already in deleted list");
            _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);
        }
    }
}

And last one Hibernate Helper:

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;
        }
        /// <summary>
        /// create hibernate config by template
        /// </summary>
        /// <returns></returns>
        public static string CreateHibernateConfig()
        {
            const string connectionconfigXml = @".\connectionconfig.xml";
            if (!File.Exists(connectionconfigXml))
                throw new ApplicationException("No Config File");
            XElement configFile = XElement.Load(connectionconfigXml);
            var config=configFile.Descendants().First();
            if(config == null)
                throw new ApplicationException("Config File bad format");

            XElement hibernateConfigs = XElement.Parse(HibernateConfigs.HibernateDialects);
            var dbTypeAttribute = config.Attribute("Type");
            if (dbTypeAttribute == null)
                throw new ApplicationException("Config File bad format. Type attribute not found");
            
            string dbConnectionType = dbTypeAttribute.Value;
            if (string.IsNullOrEmpty(dbConnectionType))
                throw new ApplicationException("Config File bad format. Type is empty");

            var connectionStringAttribute = config.Attribute("ConnectionString");
            if (connectionStringAttribute == null)
                throw new ApplicationException("Config File bad format. Connection String attribute not found");

            var connectionString = connectionStringAttribute.Value;
            if (string.IsNullOrEmpty(connectionString))
                throw new ApplicationException("Config File bad format. Connection string is empty");

            var options= hibernateConfigs.Descendants().FirstOrDefault(
                element => element.Attribute("Type").Value == dbConnectionType);
            if (options == null)
                throw new ApplicationException(string.Format("Wrong DB Connection Type:{0}", dbConnectionType));
            
            return string.Format(HibernateConfigs.HibernateConfigTemplate,options.Attribute("Driver").Value,connectionString,options.Attribute("Dialect").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("<?xml>...
            _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 && !_disposed)
            {
                Close();
                GC.SuppressFinalize(this);
            }
            _disposed = true;
        }
        ~HibernateHelper()
        {
            Dispose(false);
        }

        #endregion

    }
}

How to use if?
Example:
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();

Lyric

Follow

Get every new post delivered to your Inbox.