Friday, February 11, 2022

Asynchrony in C#

 Here is a simple example of asynchronous programming in C#:

        async static Task Task1()
        {
            Console.WriteLine("Task 1");
        }

        async static Task Task2()
        {
            Console.WriteLine("Task 2");
        }

        async static void Main(string[] args)
        {
            await Task1();
            await Task2();
        }

A Main method sequentially calling two other methods - Task1 and Task2 respectively. Thanks to magic keywords - async and await this feels intuitive, almost like synchronous programming. Without those two the above code would probably look something like that:

        static void Task1()
        {
            Console.WriteLine("Task 1");
        }

        static void Task2()
        {
            Console.WriteLine("Task 2");
        }

         static void Main(string[] args)
        {
            var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

            var task1 = Task.Factory.StartNew(() =>
            {
                Task1();
            }, default, TaskCreationOptions.None, scheduler);

            var task2 = task1.ContinueWith(task => {
                Task2();
            }, scheduler);

            task2
.Wait();
        }

Which is perfectly valid technically asynchronous programming, it's just not as elegant, although it certainly gives you deeper understanding of what's happening under the hood and most importantly much more control over the process. Speaking of control, have you ever heard of SynchronizationContext? You see, sometimes we find ourselves in a situation where there is only one thread allowed to execute specific code, for instance, a UI thread in WinForms or WPF application. What I mean is, in WinForms or WPF application all your event handlers gonna be executed on the same UI thread because their particular SynchronizationContext implementations were designed to be single-threaded. In case your wondering, WinForms implementation is WindowsFormsSynchronizationContext and WPF one is called DispatcherSynchronizationContext. So, if you have a bunch of calls and only one thread you need some kinda way to queue and order them and that's precisely what SynchronizationContext does. Or doesn't, depending on specific implementation. The default one is thread-free, which basically means it carelessly executes your tasks independently using ThreadPool.

Ok, now let's talk about ConfigureAwait. If your application has a SynchronizationContext, this means the compiler will try to execute continuations Task1 and Task2 on the same thread Main is being executed on:

        async static void Main(string[] args)
        {
            await Task1();
            await Task2();
        }

The above code is equivalent to this:

        async static void Main(string[] args)
        {
            await Task1().ConfigureAwait(true);
            await Task2().ConfigureAwait(true);
        }

But what about this one?

        async static void Main(string[] args)
        {
            await Task1().ConfigureAwait(false); /* Continuation of Main. */
            await Task2().ConfigureAwait(false); /* Continuation of Task1. */
            /* The rest of the body of Main, as in variable definitions, method calls and so on.
                Everything here is also gonna become a continuation.
            */

        }

In this case, you explicitly tell the compiler that you dont care in what SynchronizationContext and on what thread the continuations gonna be executed. This means:

  • Task1 can be executed on a different thread in a different SynchronizationContext than Main;
  • Task2 can be executed either on the same thread as Task1, which is faster than doing it on a different thread or it can be executed on any available thread;
  • Whatever comes after Task2 can be executed either on the same thread as Task2 or any available thread;

Underneath all that syntactic sugar there are three abstractions: TaskScheduler, SynchronizationContext and ThreadPool, specifically in that order.

  1. TaskScheduler schedules your tasks for execution.
  2. SynchronizationContext synchronizes task execution.
  3. ThreadPool executes your functions using a bunch of threads it's in charge of, so it couldn't care less about your asynchrony.

Here is how you create a TaskScheduler from the current SynchronizationContext:

        var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

And that's how you create a continuation using a callback and the scheduler we
previously obtained from the current SynchronizationContext:

         static void Main(string[] args)
        {
            var scheduler = TaskScheduler.FromCurrentSynchronizationContext();

            var task1 = Task.Factory.StartNew(() =>
            {
                Task1();
            }, default, TaskCreationOptions.None, scheduler);

            var task2 = task1.ContinueWith(task => {
                Task2();
            }, scheduler);

            task2.Wait();
        }

That way, Main, Task1 and Task2 are gonna be executed on the same thread and in the same SynchronizationContext.

 

Sunday, November 12, 2017

Nullable in C#

Nullable is a special generic class meant to enable value types to be set to null.

Nullable<bool> nullableOfBool = false;
Nullable<int> nullableOfInt = 0;
Nullable<float> nullableOfFloat = 0.0f;

bool? nullableOfBool = false;
int? nullableOfInt = 0;
float? nullableOfFloat = 0.0f;

As you can see you can initialize them like if they were value types. Moreover, you can treat them like value types as long as you don't mix them with actual value types:

int? v1 = 1;
int? v2 = 7;
int? result = v1 + v2;

If for some reason you wanna access underlying type, you can do this by accessing Value property of Nullable:

int v1 = 1;
int? v2 = 7;
int result = v1 + v2.Value;

Or simply cast it to a corresponding value type:

int v1 = 1;
int? v2 = 7;
int result = v1 + (int)v2;

If you don't know if your nullable contains any value, use can check it using HasValue property.

Null-conditional operator in C#

Null-conditional operator is a new .NET feature meant to ease your life as a developer. Its primary purpose is NullReferenceException prevention. I'mma give you an example:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCar(Car car)
        {
            // This is where you omitted check for null.
            string brand = car.Brand; // And this is where you get into trouble.
        }
        static void Main(string[] args)
        {
            DoSomethingWithCar(null);
        }
    }
}

Now we can either add missing check or use null-conditional operator:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCar(Car car)
        {
            // Null-conditional operator checks if car is null and if it is,
            // prevents us from accessing Brand property and sets brand to null.
            string brand = car?.Brand;
        }
        static void Main(string[] args)
        {
            DoSomethingWithCar(null);
        }
    }
}

Let's slightly modify our example so you can see another use case of null-conditional operator:

namespace ConsoleApp
{
    class Car
    {
        public string Brand { get; set; }
    }

    class Program
    {
        static void DoSomethingWithCars(Car[] cars)
        {
            // Null-conditional operator checks if cars array is null and if it is,
            // prevents us from accessing its first element and returns null.
            Car car = cars?[0];
        }
        static void Main(string[] args)
        {
            DoSomethingWithCars(null);
        }
    }
}

As you can see null-conditional operator can be used with both dot operator and subscript operator (square brackets).

Default values in C#

Here is the thing, C# doesn't allow you to leave a variable unitialized. What I mean is that every time you create a variable it's automatically assigned some sorta default value.

Integral types:
sbyte 0
byte 0
short 0
ushort 0
int 0
uint 0
long 0l
ulong 0ul

Floating-point types:
float 0.0f
double 0.0d
decimal 0.0m

Boolean:
bool false

Any class, struct, including these two:
object null
string null

Enumerations:
enum 0 (value of the first enumerator)

Characters:
char '\0'

Thursday, October 26, 2017

Tiny SSH client in C#

There is very nice SSH library for .NET called SSH.NET. You can find it here:
https://github.com/sshnet/SSH.NET, also available as a nuget package, so you can install it in a couple of clicks. Here is a brief client example:

using Renci.SshNet;
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter IP:");
            var ip = Console.ReadLine();

            Console.WriteLine("Enter username:");
            var username = Console.ReadLine();

            Console.WriteLine("Enter password:");
            var password = Console.ReadLine();

            using (var client = new SshClient(ip, username, password))
            {
                client.Connect();

                while (true)
                {
                    var input = Console.ReadLine();
                    if (input.Contains("exit my console app"))
                        break;

                    Console.WriteLine(client.RunCommand(input).Result);
                }
            }
        }
    }
}

OpenVPN Jumpstart

Yesterday I badly needed to establish VPN connection between two computers, nothing extraordinary, one server and one client. In order to accomplish this quite trivial task I created a key:

openvpn --genkey --secret whatever.key

and two configuration files for the server(192.168.1.1):

dev tun
ifconfig 10.0.0.1 10.0.02
secret whatever.key

and the client(192.168.1.2) respectively:

remote 192.168.1.1
dev tun
ifconfig 10.0.0.2 10.0.01
secret whatever.key

Then I just ran:

openvpn --config server.conf
openvpn --config client.conf

and surprisingly it worked :)

By the way, if you have some kinda firewall or something you might need to consider opening port 1194.

Expression Bodied Functions and Properties in C#

Since C# 6 you can take advantage of using much more laconic expression bodied functions. Oh, expression bodied basically means lambdish or just bodiless :)

using System;

namespace ConsoleApp
{
    class Program
    {
        static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);

        static void Main(string[] args)
        {
            ExpressionBodiedMethod("Hello!");
        }
    }
}

That shortened syntax can also be used to create a getter-only property:

using System;

namespace ConsoleApp
{
    class Program
    {
        static string ExpressionBodiedReadOnlyPrpoperty => "Hello!";
        /*static string ExpressionBodiedReadOnlyPrpoperty { get; } = "Hello!";*/

        static void ExpressionBodiedMethod(string str) => Console.WriteLine(str);

        static void Main(string[] args)
        {
            ExpressionBodiedMethod(ExpressionBodiedReadOnlyPrpoperty);
        }
    }
}

Thursday, October 19, 2017

Async and Await in C#

It's possible to do asynchronous programming in C#. In order to ease your life a little bit they came up with the idea to add a couple of extra keywords: async and await.

using System;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int result = DoSomeJobAsync().Result;

            Console.WriteLine("Result: " + result);
        }

        async static Task<int> DoSomeJobAsync() {
            return await Task.Run(() => { return 777; });
        }
    }
}

So, to tell compiler you want your method to be "asynchronous" you have to prepend it with async keyword which enables you to use await keyword inside it in order to create so-called suspension point which is basically the asynchronous equivalent of  blocking. The whole concept is meant to manage asynchronous and synchronous calls separately, but I'll tell you what, it's impossible and if you disagree, take a look at what happens in Main. As we cannot use await in synchronous method we are forced to block until we get the result from asynchronous chain of methods.

Tuesday, October 17, 2017

Simple data binding in WPF

Data binding in WPF is how you pass data between your code and user interface. The simplest way to bind some data is to use DataContext property. Each element has its own DataContext property, which if not set, inherits its value from parent element. In the example below all elements are gonna inherit DataContext from MainWindow.

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new Location();
        }
    }

    public class Location
    {
        public string Country { get; set; }
        public string State { get; set; }
        public string City { get; set; }

        public Location()
        {
            Country = "Russian Federation";
            State = "Sverdlovsk";
            City = "Yekaterinburg";
        }
    }
}

<Window x:Class="WpfApp.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:local="clr-namespace:WpfApp"
  mc:Ignorable="d"
  Title="MainWindow" Height="350" Width="525">
    <Grid>
      <Label Content="Country:"
        HorizontalAlignment="Left"
        Margin="29,21,0,0"
        VerticalAlignment="Top"/>

       <Label Content="State:"
         HorizontalAlignment="Left"
         Margin="29,70,0,0"
         VerticalAlignment="Top"/>

       <Label Content="City:"
         HorizontalAlignment="Left"
         Margin="29,125,0,0"
         VerticalAlignment="Top"/>
     
        <TextBox HorizontalAlignment="Left"
          Height="23"
          Margin="29,49,0,0"
          TextWrapping="Wrap"
          Text="{Binding Country, Mode=OneWay}"
          VerticalAlignment="Top"
          Width="120"/>

        <TextBox HorizontalAlignment="Left"
          Height="23"
          Margin="29,99,0,0"
          TextWrapping="Wrap"
          Text="{Binding State, Mode=OneWay}"
          VerticalAlignment="Top"
          Width="120"/>

        <TextBox HorizontalAlignment="Left"
          Height="23"
          Margin="29,154,0,0"
          TextWrapping="Wrap"
          Text="{Binding City, Mode=OneWay}"
          VerticalAlignment="Top"
          Width="120"/>
    </Grid>
</Window>

Ok, now all texboxes have text field set to corresponding Location property's value. But what if we also wanna set whatever user enters in textbox to corresponding Location property's value? We can easily do this by simply changing binding mode from OneWay to TwoWay.

<Window x:Class="WpfApp.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:local="clr-namespace:WpfApp"
  mc:Ignorable="d"
  Title="MainWindow" Height="350" Width="525">
    <Grid>
      <Label Content="Country:"
        HorizontalAlignment="Left"
        Margin="29,21,0,0"
        VerticalAlignment="Top"/>

       <Label Content="State:"
         HorizontalAlignment="Left"
         Margin="29,70,0,0"
         VerticalAlignment="Top"/>

       <Label Content="City:"
         HorizontalAlignment="Left"
         Margin="29,125,0,0"
         VerticalAlignment="Top"/>
     
        <TextBox HorizontalAlignment="Left"
          Height="23"
          Margin="29,49,0,0"
          TextWrapping="Wrap"
          Text="{Binding Country, Mode=TwoWay}"
          VerticalAlignment="Top"
          Width="120"/>

        <TextBox HorizontalAlignment="Left"
          Height="23"
          Margin="29,99,0,0"
          TextWrapping="Wrap"
          Text="{Binding State, Mode=TwoWay}"
          VerticalAlignment="Top"
          Width="120"/>

        <TextBox HorizontalAlignment="Left"
          Height="23"
          Margin="29,154,0,0"
          TextWrapping="Wrap"
          Text="{Binding City, Mode=TwoWay}"
          VerticalAlignment="Top"
          Width="120"/>
    </Grid>
</Window>


Monday, October 16, 2017

finally block and using statement in C#

In addition to try and catch C# got so-called finally block whose purpose is to free resources allocated within try block.

using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = null;

            try
           {
                sw = new StreamWriter("myFile.txt");
                sw.WriteLine("Hello");
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
            }
        }
    }
}

finally block will get executed even if something in your try block throws an exception. There is much more convenient way to create try-finally block around your code though, its called using statement:

using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            using(StreamWriter sw = new StreamWriter("myFile.txt"))
           {
                sw.WriteLine("Hello");
            }
        }
    }
}

If you need to be able to handle exception you're gonna have to use the previous syntax plus catch block as using statement can't help you with that:

using System.IO;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter sw = null;

            try
           {
                sw = new StreamWriter("myFile.txt");
                sw.WriteLine("Hello");
            }
            catch(IOException e)
            {
             // Handle exception before resource gets freed in finally block.
            }
            finally
            {
                if (sw != null)
                {
                    sw.Dispose();
                }
            }
        }
    }
}

Extension methods in C#

C# got very interesting feature allowing you to add a method to existing class. Here is what it looks like:

namespace ConsoleApp
{
    class A
    {
        public double value { get; set; }

        public A()
        {
            value = 7.0;
        }
    }

    static class ExtensionMethods
    {
        public static double ComputeReciprocal(this A a)
        {
            return 1.0 / a.value;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var a = new A();
            var value = a.value;
            var reciprocal = a.ComputeReciprocal();
        }
    }
}

C# successfully recognized ComputeReciprocal as A class extension method and let us call it like if it belonged to the class. Please pay attention to extension method parameter list, the first parameter always has to be: this ClassName parameterName, after the first parameter you can add as many additional parameters as you want:

namespace ConsoleApp
{
    class Person
    {
        public string FirstName { get; set; }

        public Person()
        {
            FirstName = "Alex";
        }
    }

    static class ExtensionMethods
    {
        public static string GetFullName(this Person person, string lastName)
        {
            return person.FirstName + " " + lastName;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person();
            var fullName = person.GetFullName("Peters");
        }
    }
}

By the way, it doesn't matter what you call static class which contains your extension methods.



Increment and Decrement operator overloading in C++

In C++ you can overload both prefix and postfix increment and decrement operators like that:

class Dummy
{
public:
Dummy() :value(0) {}
Dummy(int pmValue) : value(pmValue) {}
Dummy(const Dummy& dummy) : value(dummy.getValue()) {}

int getValue() const
{
return value;
}
//---------------------------------------- Prefix
Dummy& operator++()
{
++value;

return *this;
};

Dummy& operator--()
{
--value;

return *this;
};
//---------------------------------------- Postfix
Dummy operator++(int)
{
Dummy lvDummy(*this);
++value;

return lvDummy;
};

Dummy operator--(int)
{
Dummy lvDummy(*this);
--value;

return lvDummy;
};

private:
int value;
};

If you had a problem with postfix ones, you just needed to add a parameter. Keep in mind that according to C++ standard (page 327, 13.5.7), the parameter must be int. Oh, you can also overload all of them globally following the same principle:

class Dummy
{
public:
Dummy() :value(0) {}
Dummy(const Dummy& dummy) : value(dummy.value) {}
Dummy(int pmValue) : value(pmValue) {}

int value;
};

Dummy& operator ++ (Dummy& dummy) {
++dummy.value;

return dummy;
}

Dummy& operator -- (Dummy& dummy) {
--dummy.value;

return dummy;
}

Dummy operator ++ (Dummy& dummy, int) {
Dummy lvDummy(dummy);
++dummy.value;

return lvDummy;
}

Dummy operator -- (Dummy& dummy, int) {
Dummy lvDummy(dummy);
--dummy.value;

return lvDummy;
}


Sunday, October 15, 2017

Move constructor and assignment operator in C++

In addition to copy constructor and assignment operator C++ got so-called move constructor and assignment operator. First I am gonna show you what copy constructor and assignment operators are:

class A
{
public:
    int* some_data;

    A()
    {
        some_data = new int[128];
    }

   // Copy constructor
   A(const A& a)
   {
        some_data = new int[128];
        memcpy(some_data, a.some_data, 128);
   }

    ~A()
    {
        delete[] some_data;
    }

// Assignment operator
    A& operator = (const A& a)
    {
        if (this != &a)
       {
            delete[] some_data;
            some_data = new int[128];
            memcpy(some_data, a.some_data, 128);
       }
       return *this;
    }
};

int main()
{
A a1;
A a2(a1); // Copy constructor call
A a3;
a3 = a1; // Assignment operator call

return 0;
}

As you can see both copy constructor and assignment operator do exactly the same thing, they create a copy of other instance of the same class. In the example above, copying maybe slightly optimized using move constructor and move assignment operator:

class A
{
public:
  int* some_data;

    A()
   {
        some_data = new int[128];
   }

    // Move constructor
    A(A&& a)
   {
        some_data = a.some_data;
        a.some_data = nullptr;
}

~A()
  {
delete[] some_data;
}

  // Move assignment operator
A& operator = (A&& a)
 {
if (this != &a)
{
          delete[] some_data;
          some_data = a.some_data;
          a.some_data = nullptr;
}

return *this;
  }
};

int main()
{
A a1;
A a2(std::move(a1)); // Move constructor call
A a3;
a3 = std::move(a1); // Move assignment operator call

return 0;
}

In other words, move constructor and move assignment operator are merely optimized versions of regular copy constructor and assignment operator.



C++ inheritance flavors

C++ has 4 types of inheritance. Let's start with public inheritance:

class A {
public:
void one() {}
protected:
void two() {}
private:
void three() {}
};

class B : public A {};

Public inheritance implies that class B inherits all public and protected methods from class A as is. This is what signature of class B looks like now:

class B : public A
{
public:
void one() {}
protected:
void two() {}
};

Let's move on and take a look at protected inheritance as well:

class B : protected A
{
protected:
void one() {}
void two() {}
};

As you can see the difference between the two is that all public methods of class A become protected in class B. Now, guess what happens when you use private inheritance? This is what happens:

class B : private A
{
private:
void one() {}
void two() {}
};

All public and protected methods inherited from A become private. Ok, I said there are 4, the fourth one is so-called virtual inheritance which allows you to literally share your base class when, for instance to fight famous diamond problem. Let's create some kinda diamond for clarity:

class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}

void topMethod() {}
};

class Left : public Top
{
public:
void leftMethod()
{
topMethod();
}
};


class Right : public Top
{
public:
void rightMethod()
{
topMethod();
}
};


class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};

Despite the fact that there will be two Top classes in our hierarchy, this will compile and run like it's no problem. Please run it and you'll see that Top constructor gets called twice. If such a behavior bothers you, you can get rid of the second Top class using virtual inheritance:

class Top
{
public:
Top()
{
std::cout << "Hello, I am the top." << std::endl;
}

void topMethod() {}
};

class Left : public virtual Top
{
public:
void leftMethod()
{
topMethod();
}
};


class Right : public virtual Top
{
public:
void rightMethod()
{
topMethod();
}
};


class Bottom : public Left, public Right
{
public:
void bottomMethod()
{
leftMethod();
rightMethod();
}
};

Now, run it again to make sure we have only one Top.

Multithreading in C++

Since C++ 11 multithreading in C++ became a lot easier. You no longer need to wrap system specific stuff like threads and synchronization primitives yourself as they all are already there. Ok, let's get to it. In modern C++ you can spawn a new thread as easy as that:

#include <thread>

void threadFunction() {}

int main()
{
    std::thread thread(threadFunction);
    thread.join();

    return 0;
}

Now, let's talk about synchronization, starting with Mutex. Mutex is a quite simple synchronization primitive meant for protecting a resource from accessing by multiple threads at the same time. Here is what it looks like:

#include <thread>
#include <mutex>

std::mutex mutex;
int resource = 2;

void threadFunction()
{
    std::lock_guard<std::mutex> lock(mutex);

    resource *= 2;
}

int main()
{
    std::thread thread1(threadFunction);
    std::thread thread2(threadFunction);

    thread1.join();
    thread2.join();

    return 0;
}

As you can see from the example above we successfully protected our resource variable from accessing by multiple threads using mutex. You probably noticed that we used std::lock_guard template class to lock our mutex, well std::lock_guard is that exact lock wrapper we used to make ourselves before C++11 arrival. If you forgot how it works, its very simple. It locks mutex upon construction and then releases it upon destruction when we leave function body scope. You may be wondering why cant you lock and unlock mutex whenever you need using std::lock_guard, well, thats because std::lock_guard follows so-called scope ownership which prevents you from managing your lock in any way. If you need to manage your lock you kinda have to use a different kinda lock which is std::unique_lock.

#include <thread>
#include <mutex>

std::mutex mutex;
int resource = 2;

void threadFunction()
{
    std::unique_lock<std::mutex> lock(mutex);

    resource *= 2;

    lock.unlock();
}

int main()
{
    std::thread thread1(threadFunction);
    std::thread thread2(threadFunction);

    thread1.join();
    thread2.join();

    return 0;
}

As you can see std::unique_lock is much more flexible when it comes to a lock management. Talking about flexibility, there is one more synchronization primitive I'd like to show you, which is a condition variable. Let's slightly modify our example to use this primitive:


#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mutex;
std::condition_variable condition_variable;
int resource = 2;

void threadFunction()
{
    // Lock or if we can't block as usual
    std::unique_lock<std::mutex> lock(mutex);
    // Successfully acquired lock, now we can access our std::condition_variable.

    // Calling wait method, which blocks this thread and releases lock.
    condition_variable.wait(lock);
    // If we got here it means main thread called condition_variable.notify_all(),
    // which resulted in unblocking current thread and reacquiring lock.

    // We can thread-safely mess with out beloved resource.
    resource *= 2;
}

int main()
{
    std::thread thread1(threadFunction);
    std::thread thread2(threadFunction);

    std::unique_lock<std::mutex> lock(mutex);
    condition_variable.notify_all();

    thread1.join();
    thread2.join();

    return 0;
}

Ok, now let me try to explain to you what's going on in here. First of, as you can see, we still use locks to protect our resource. Well, actually we protect both our resource and std::condition_variable whose purpose is to unblock all threads waiting on it and then reacquire locks upon notification from other thread, which, in our example, happens to be main thread. Yes, I know, my example is way too trivial to be practical, but it wasn't the goal here, I merely wanted to explain the idea.