Posts tagged ‘multithreading’
One of my friends recently asked me about the multithreading in C# so that many jobs can work on a same shared data. Like many programming languages, C# has its own libraries to support this need. Let me firstly describe a little bit about multithreading.
In the trend of increasing number of cores integrated in the same processor chip, you may wonder “How do I utilize all available cores to make my program run faster?”. I guess that most of programs you’ve ever written till now are in sequential model. In this model, only one job is executed at a time and all jobs are finished in a sequential order. However, if you do a review of your programs and find some jobs can be run parallelly, multithreading can be a good choice to answer your question. Using a right multi-thread programming model can speed up your program if it runs on a machine with multi-processor/multi-core. However, this is not the only purpose of using many threads in a program. Another purpose of multithreading is interaction. For example, your program provides a service that may be requested by many clients at the same time. Instead of letting the clients queue and wait for their turns, the program can accept all requests and process them concurrently. At the result, all clients can receive the responses at the time of request.
A multi-thread program is enabled by using multithreading libraries such as OpenMP, Pthreads, Java Threads, Windows API threads… I don’t know exactly how many libraries of this type but I’m sure there are a lot. Some of them are created by companies like Microsoft, Intel while the others are born by research groups in universities or organizations. My professor developed her own one for writting programs running on Cray or similar machines. In practice, each programming language has one or many tools that support multithreading. So which one should I choose? It is very hard to answer this question since it depends on the usage purpose, computing model and the programming language of your program.
In C#, the System.Threading namespace gives you a number of types that enable multithreading programming. In this post, I did a small example program demonstrating how to do multithreading in C# GUI application. In the program, two threads are created and work on a same shared text data. One thread is scrolling in the text data from right the left and the other does the scrolling of same text in the reverse direction. Below is the program screenshot.
Download source code here