Wednesday, June 11, 2014

Multithreading 2

Multithreading Implementation
The following section plays with the numerous System.Threading namespace static and instance-level members and properties.
Obtaining Current Thread Information’s
To illustrate the basic use of Thread type, suppose you have console application in which CurrentThread property retrieves aThread object that represents the currently executing thread.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Threading;
 
namespace threading
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("**********Current Thread Informations***************n");
            Thread t = Thread.CurrentThread;
            t.Name = "Primary_Thread";
 
            Console.WriteLine("Thread Name: {0}", t.Name);
            Console.WriteLine("Thread Status: {0}", t.IsAlive);
            Console.WriteLine("Priority: {0}", t.Priority);
            Console.WriteLine("Context ID: {0}", Thread.CurrentContext.ContextID);
            Console.WriteLine("Current application domain: {0}",Thread.GetDomain().FriendlyName);
 
            Console.ReadKey();
        }
 
    }
}
After compiling this application, the output would be as following;
Simple Thread Creation
The following simple example explains the Thread class implementation in which the constructor of Thread class accepts a delegate parameter. After the Thread class object is created, you can start the thread with the Start() method as following;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Threading;
 
namespace threading
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(myFun);
            t.Start();
 
            Console.WriteLine("Main thread Running");
            Console.ReadKey();
        }
 
        static void myFun()
        {
            Console.WriteLine("Running other Thread");
        }
    }
}
After running the application, you got the following output of the two threads as:
The important point to be noted here is that, there is no guarantee what output come first meaning, which thread start first. Threads are scheduled by the operating system. So which thread comes first can be different each time.
Background Thread
The process of the application keeps running as long as at least one foreground thread is running. If more than one foreground thread is running and the Main() method ends, the process of the application keeps active until all foreground threads finish their work.
When you create a thread with the Thread class, you can define if it should be a foreground or background thread by setting the property IsBackground. The Main() method set this property of the thread t to false. After setting the new thread, the main thread just writes to the console an end message. The new thread writes a start and an end message, and in between it sleep for two seconds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Threading;
 
namespace threading
{
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(myFun);
            t.Name = "Thread1";
            t.IsBackground = false;
            t.Start();
            Console.WriteLine("Main thread Running");
            Console.ReadKey();
        }
 
        static void myFun()
        {
            Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name);
            Thread.Sleep(2000);
            Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name);
        }
    }
}
When you compile this application, you will still see the completion message written to the console because the new thread is a foreground thread. Here, the output as following;
If you change the IsBackground property to start the new thread to true, the result shown at the console is different as follows:
Concurrency issues
Programming with multiple threads is not an easy task. When starting multiple threads that access the same data, you can get intermediate problems that are hard to resolve. When you build multithreaded applications, you program needs to ensure that any piece of shared data is protected against the possibility of numerous threads changing its value.
Race Condition
A race condition can occurs if two or more threads access the same objects and access to the shared state is not synchronized. To illustrate the problem of Race condition, let’s build a console application. This application uses the Test class to print 10 numbers by pause the current thread for a random number of times.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
Using System;
using System.Threading;
 
namespace threading
{
    public class Test
    {
        public void Calculation()
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(new Random().Next(5));
                Console.Write(" {0},", i);
            }
            Console.WriteLine();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();
            Thread[] tr = new Thread[5];
 
            for (int i = 0; i < 5; i++)
            {
                tr[i] = new Thread(new ThreadStart(t.Calculation));
                tr[i].Name = String.Format("Working Thread: {0}", i);
            }
 
            //Start each thread
            foreach (Thread x in tr)
            {
                x.Start();
            }
            Console.ReadKey();
        }
    }
}
After compiling this program, the primary thread within this application domain begins by producing five secondary threads. Each working threads told to call the Calculate method on the same Test class instance. So you have taken none of precaution to lock down this object’s shared resources. Hence, all of five threads start to access the Calculation method simultaneously. This is the Race Condition and the application produce unpredictable output as following;
Deadlocks
Having too much locking into an application can get your application into trouble. In a deadlock, at least two threads wait for each other to release a lock. As both threads wait for each other, a deadlock situation occurs and thread wait endlessly and your computer eventually hanged.
Here, the both of methods changed the state of the two objects obj1 and obj2 by locking them. The methods DeadLock1() first lock obj1 and next for obj2. The method DeadLock2() first lock obj2 and then obj1.So lock for obj1 is resolved next thread switch occurs and second method start to run and gets the lock for obj2. The second thread now waits for the lock of obj1. Both of threads now wait and don’t release each other. This is typically deadlock.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Threading;
 
namespace threading
{
    class Program
    {
        static object obj1 = new object();
        static object obj2 = new object();
 
        public static void DeadLock1()
        {
            lock (obj1)
            {
                Console.WriteLine("Thread 1 got locked");
                Thread.Sleep(500);
                lock (obj2)
                {
                    Console.WriteLine("Thread 2 got locked");
                }
            }
        }
 
        public static void DeadLock2()
        {
            lock (obj2)
            {
                Console.WriteLine("Thread 2 got locked");
                Thread.Sleep(500);
                lock (obj1)
                {
                    Console.WriteLine("Thread 1 got locked");
                }
            }
        }
 
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(DeadLock1));
            Thread t2 = new Thread(new ThreadStart(DeadLock2));
 
            t1.Start();
            t2.Start();
 
           Console.ReadKey();
        }
 
    }
}

by http://resources.infosecinstitute.com/multithreading/

Multithreading

Introduction
The term “multithread programming” may sound complicated, but it is quite easy to do in C#.net. This article explains how multithreading works on your typical, general-purpose computer. You will learn how the operating system manages thread execution and how to manipulate the Thread class in your program to create and start managed threads. This article also renders the information you need to know when programming application with multiple threads such as Thread class, pools, threading issues and backgroundWorker.
Multithreading Overview
A thread is an independent stream of instructions in a program. Each written program is a paradigm of sequential programming in which they have a beginning, an end, a sequence, and a single point of execution. A thread is similar to sequential program. However, a thread itself is not a program, it can’t run on its own, but runs within a program.
The real concern surrounding threads is not about a single sequential thread, but rather the use of multiple threads in a single program all running at the same time and performing different tasks. This mechanism referred as Multithreading. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of resources allocated for that program.
Threads are important both for client and server applications. While in C# program coding, when you type something in editor, the dynamic help (intellisense) Windows immediately shows the relevant topics that fit to the code. One thread is waiting for input from the user, while other does some background processing. A third thread can store the written data in a temporary file, while another one downloads a file from a specific location.
With the task manager, you can turn on the Thread column and see the processes and the number of threads for every process. Here, you can notice that only cmd.exe is running inside a single thread while all other applications use multiple threads.
The operating system schedules threads. A thread has priority and every thread has its own stack, but the memory for the program code and heap are shared among all threads of a single process.
A process consists of one or more threads of execution which is simply referred as threads. A process always consists of at least one thread called as Main thread (Main() method). A single thread process contains only one thread while multithread process can contains more than one thread of execution.
On a computer, the operating system loads and starts applications. Each application or service runs as a separate process on the machine. The following image illustrates that there are quite few processes actually running than there are applications. Many of the processes are background operating system processes that are started automatically when the computer powers up.
System.Threading Namespace
Under .NET platform, the System.Threading namespace provides a number of types that enable the direct construction of multithreaded application.
TypeDescription
ThreadIt represents a thread that execute within the CLR. Using this, we can produce additional threads in application domain.
MutexIt is used for synchronization between application domains.
MonitorIt implements synchronization of objects using Locks and Wait.
SmaphoreIt allows limiting the number of threads that can access a resource concurrently.
InterlockIt provides atomic operations for variables that are shared by multiple threads.
ThreadPoolIt allows you to interact with the CLR maintained thread pool.
ThreadPriorityThis represents the priority level such as High, Normal, Low.
System.Threading.Thread class
The Thread class allows you to create and manage the execution of managed threads in your program. They are called managed threads because you can directly manipulate each thread you create. You will found the Thread class along with useful stuffs in the System.Threading namespace.
MemberTypeDescription
CurrentThreadStaticReturn a reference of current running thread.
SleepStaticSuspend the current thread for a specific duration.
GetDoaminStaticReturn a reference of current application domain.
CurrentContextStaticReturn a reference of current context in which the thread currently running.
PriorityInstance levelGet or Set the Thread priority level.
IsAliveInstance levelGet the thread state in form of True or False value.
StartInstance levelInstruct the CLR to start the thread.
SuspendInstance levelSuspend the thread.
ResumeInstance levelResume a previously suspended thread.
AbortInstance levelInstruct the CLR to terminate the thread.
NameInstance levelAllows establishing a name to thread.
IsBackgroundInstance levelIndicate whether a thread is running in background or not.

Multithreading

All multitasking systems have a scheduler. A scheduler decides what unit of work will execute next. A basic scheduler can be something that runs of a high resolution timer (like, say, every 100ms, a task switch happens). Clearly, modern implementations are much more complicated than that.
That said, most modern threading implementations rely on a scheduler within the kernel. Many of these schedulers are NOT deterministic. That is, there is no guarantee that a context switch (i.e. a switch between runnable instances managed by the scheduler) will happen at any specific time.
What you are seeing are the discrepancies in that scheduler for your system.

Wednesday, June 4, 2014

Thread vs Task


Thread

Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.
The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.
There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.

ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.
Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.
Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith()on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic,ContinueWith() will pass you the task's result, allowing you to run more code that uses it.
You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.
Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.
All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built onTask.

Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.
The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

source : http://blog.slaks.net/

Wednesday, December 26, 2012

Google Tricks


1.Do a  barrel Roll

Another cool Google trick that has been doing the rounds on the internet is the barrel roll. Just type 'do a barrel roll' in your browser and you will see the whole page spin 360-degrees once. Just refresh the page to see the effect again and again.

2.Zerg Rush

Just punch 'Zerg Rush' in Google and you will find yourself defending your search results from an onslaught of zerglings that will try to eat them up. Want to save your precious search results from being obliterated? Just repeatedly click on the dastardly zerglings (which are basically red and yellow coloured Os) to eliminate them. 

What's more, Google is keeping score! A widget on the right side of the screen will show how many times you clicked to kill the enemy and the number you killed. If you are unsuccessful, the yellow and red coloured Os will wipe out all search results and assemble to form 'GG'. You can share the score with your circles on Google+ or clear the game and move on to search results.

Monday, November 5, 2012

C# Regular Expressions Cheat Sheet

C# Regular Expressions Cheat Sheet

Cheat sheet for C# regular expressions metacharacters, operators, quantifiers etc
Character
Description
\Marks the next character as either a special character or escapes a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".
Note: double quotes may be escaped by doubling them: ""
^Depending on whether the MultiLine option is set, matches the position before the first character in a line, or the first character in the string.
$Depending on whether the MultiLine option is set, matches the position after the last character in a line, or the last character in the string.
*Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".
+Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".
?Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".
.Matches any single character except a newline character.
(pattern)Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\(" or "\)".
(?pattern)Matches pattern and gives the match a name.
(?:pattern)A non-capturing group
(?=...)A positive lookahead
(?!...)A negative lookahead
(?<=...)A positive lookbehind .
(?<!...)A negative lookbehind .
x|yMatches either x or y. For example, "z|wood" matches "z" or "wood". "(z|w)oo" matches "zoo" or "wood".
{n}n is a non-negative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".
{n,}n is a non-negative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".
{n,m}m and n are non-negative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".
[xyz]A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".
[^xyz]A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".
[a-z]A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".
[^m-z]A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".
\bMatches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".
\BMatches a non-word boundary. "ea*r\B" matches the "ear" in "never early".
\dMatches a digit character. Equivalent to [0-9].
\DMatches a non-digit character. Equivalent to [^0-9].
\fMatches a form-feed character.
\kA back-reference to a named group.
\nMatches a newline character.
\rMatches a carriage return character.
\sMatches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".
\SMatches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".
\tMatches a tab character.
\vMatches a vertical tab character.
\wMatches any word character including underscore. Equivalent to "[A-Za-z0-9_]".
\WMatches any non-word character. Equivalent to "[^A-Za-z0-9_]".
\numMatches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.
\nMatches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.
\xnMatches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.
\unMatches a Unicode character expressed in hexadecimal notation with exactly four numeric digits. "\u0200" matches a space character.
\AMatches the position before the first character in a string. Not affected by the MultiLine setting
\ZMatches the position after the last character of a string. Not affected by the MultiLine setting.
\GSpecifies that the matches must be consecutive, without any intervening non-matching characters.