Parallelism vs Async / Non- Blocking (Introduction)

When to use threads vs async?

Creating a new thread in software application will have least 2 threads including a main thread in parallel programming approach.

Threads vs cores in CPU

Almost every computer today contains at least 2 cores, in CPU. But not many computer programs get the full benefits of maximum utilization of cores in a processor.

  1. Design proper threading architectural strategy to share the threads across multiple cores

Threads in parallelism

Use the namespace below to get started:

using System.Threading;
Thread newWorkerThread = new Thread(() => SyncDataToCloud());
newWorkerThread.Start();

Multi threading Vs Performance

Multi threading environments often lead to performance degradation than increment, particularly when the threads sharing resources with each other.

C# Tasks Parallel Library (TPL)

TPL creates a supporting mechanism that allows engineers to always effectively work with thread pool, unlike the scenario where directly creating a new thread by application. Thread pooling helps to work on thread affinity to run applications across less used cores. That is a optimal strategy to achieve best possible performance outcome on CPU usage.

using System.Threading.Tasks;
Task.Run(() => SyncDataToCloud());
ThreadPool.SetMaxThreads(4, 4);
ThreadPool.SetMinThreads(1, 1);

Threads Safety

There are some scenarios, functions run in multiple threads has to manage carefully to avoid unexpected failures or inaccuracy. Especially when multiple threads are accessing same resources such as application variables.

int bankBalance;void CreditAccount(int amount)
{
bankBalance = bankBalance + amount;
saveBalance(bankBalance);
}
void DebitAccount(int amount)
{
bankBalance = bankBalance - amount;
saveBalance(bankBalance);
}
void saveBalance(int balance)
{}
Task.Run(() => CreditAccount(1000));//Below statement can be trigger from a different eventTask.Run(() => DebitAccount(1000));

How to use a lock

Easiest way to ensure the reliability of debit and credit functions is to introduce a lock code block. Lock will keep other threads on wait till the current code block completed execution.

static readonly object _object = new object();void CreditAccount(int amount)
{
lock (_object)
{
bankBalance = bankBalance + amount;
saveBalance(bankBalance);
}}void DebitAccount(int amount)
{
lock (_object)
{
bankBalance = bankBalance - amount;
saveBalance(bankBalance);
}}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hasitha A

Hasitha A

A Software Architect based in Singapore.