Wednesday, August 3, 2011

Multithreading

I believe if you are proffesional you dont care what language you need to implement things. You just need to know concept and operating system feautures.
Today i want to talk about multithreading
Again, i dont care about C/C++/Java/C#.
Once you know the concept, in 10 minutes you can find evrything you know
Lets start from what is thread?
thread of execution is the smallest unit of processing that can be scheduled by an operating system.
Meaning
We have our hardware, we have our operating system. Inside of operatin system we have scheduler - a unit that executes and multiplexes all the processes.
For example, you have MS word and Outlook opened. You have 2 processes that run.
Now,
We have main thread everytime we start process. If we want to do something in background : for example, listen to events that may occure, calculate some value etc we need to run some additional task.
So basically we need to make some job, describe the rutine and tell the operatin system that it should run in separate thread.
Lets code :
First C++ a little
As we know this is great and fast but not too portable!
WRONG!
It is.If u use some wrapper that will wrape all the differences behind the screen.
Such a wrapper is ACE The ADAPTIVE Communication Environment - is freely avalible.
Once u write for ACE the only thing u need to do is recompile your code on different OS.
example:
http://www.cs.bgu.ac.il/~spl041/practsession/tirgul10/Example1/Simple_Thread_using_ACE.html
Here we go! we have Thread in C++ platform independly
Now Java
Same
1. Implement Runnable interface
public class HelloRunnable implements Runnable {

public void run() {
System.out.println("Hello from a thread!");
}

2. Run the thread

public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}

C# ??? I dont care :)
http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.80).aspx
Its almost same :)
Juts u need to tell what method u want to use like executable
Next we will intriduce syncronization