Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
6. Parallelism: threads
//6. Parallelism: threads using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace Rextester { public class Program { public static void Main(string[] args) { //Modern operating systems support multitasking. This means that multiple programs (or processes) may run simultaneously even on a single cpu. //This is achieved by switching from one process to another many times per second (i.e. one process gets to execute its instructions, then another one and so on). //Threads are simillar to processes, but they run inside one process. //So threads are isolated chunks of code that run "simultaneously". They are usefull because they let utilise many cpus and this way speedup algorithms. //Imagine you need to fetch 1000 web pages from the web. You could do it in serial: first fetch one, then the second one and so on. //Or you could spawn 1000 threads and fetch them all in parallel. //The oldest way to start a thread in C# is to use Thread class: var thread = new Thread(f => { Thread.Sleep(5000); //this will put current thread to sleep for 5 seconds. //This means that this thread won't be given any cpu time for the next 5 seconds. Console.WriteLine("Hello from another thread!"); }); thread.Start(); Console.WriteLine("Hello from main thread!"); thread.Join(); //wait for spawned thread to end //One thing to keep in mind is creating threads with Thread class is an expensive way since it takes for some time and memory to initialise new thread. //Much cheaper way is to use already initialised thread from a ThreadPool. After your thread ends it is put back to the pool for later usage. ThreadPool.QueueUserWorkItem(f => { Console.WriteLine("Hello from another thread (taken from the pool this time!)"); }); //Finally the latest and the hottest way to launch threads is by using Tasks from System.Threading.Tasks namespace. Thread from a pool will be used, so it is as cheap as before. var task = Task.Run(() => { Console.WriteLine("Hello from task-created thread!"); }); task.Wait(); //wait for the task to finish } } }
run
|
edit
|
history
|
help
0
Events
Switch
Min Max Sum Avg
Planet-D v.0.6
Rijndael
Lambda Expression
ERFDAX
sdfghnjmkuyhtgrfed
Store reference to a object
Customised Code Dashboard