Thursday, August 1, 2019

Exploring a Multi-Threaded Hello World

Having fun with Threads on the casual day

They do say sharing is caring

In our intro C++ tutorial, we started to explore writing our HelloWorld program going from a simple implementation to one with a little more spice. Here we are going to break down our last example which achieves our goals of global salutations using C++’s std::thread library.

Let’s start with the code.


In this HelloWorld program, we wanted to fire off two threads each print “Hello” and “World” respectively. Sounds simple enough. However, since both threads will begin to execute immediately from creation, we need to control the order in which they both print. This is because there is no way to determine which order the scheduler, a thread execution scheduling system, will run our threads.

So, here is the plan. We will use one thread for each word. We will ensure the second thread cannot print “World” till the first has printed “Hello”. We can orchestrate this behavior using the std::mutex and std::conditional_variable libraries. You can think of a Mutex as a key to the public bathroom at a coffee shop - only one person can use the key and access the bathroom. Others need to wait for the key to be released. A conditional variable allows us to add further locking constraints. In our key to the coffee shop bathroom example, a conditional variable adds a constraint such as even if you have a key, the bathroom needs to be free before getting in if its a single person stall. (You never thought you’d be reading about a bathroom at a coffee shop right? Stay with me here). Thus together, the key and the condition of “bathroom not in use” control ordered access to using the bathroom by multiple patrons - in our case, multiple threads.

With the code and high level approach in mind, let’s walk the code.

First we include our need libraries, “<thread>”, “<mutex>”, “<condition_variable>”, and “<iostream>”. We have a global boolean “goforit” which will serve as our flag for the condition_variable. Next, we define our “mutex” and “condition_variable”. They will come into play in the threads. Now, we introduce our first thread which will print our “Hello”. For our threads, we are passing in Lambdas as input which are anonymous functions containing blocks of code they will execute. In the constructor, we define our lambda by first stating what variables it captures. In this case, our captured variables are for controlling our thread execution ordering. We capture these by reference hence the ampersand qualifier.

In the Lambda block, we immediately print “Hello”. Given that it needs to print first, we can go ahead and make the print. Next we create an additional scope and in it, we create a lock_guard around our created “lock” holding the lock from other threads. We flip our flag “goforit” to true and call notify on our conditional_variable in case a thread is listening. A thread will be listening on our condition_variable if the condition failed and thus will wait to be notified again to check the condition. Our extra scope, created by the curly brackets allows us to let the destruction of created variable to be handled by the runtime. This is great because when our “lock_guard” is destroyed, it releases the key automagically for us.

Our second thread follows a similar pattern. Created with a lambda being passed, the lambda captures our execution control variables but this time it doesn’t print “World” immediately. Since we don’t know if “Hello” was printed, we check our condition_variables before we proceed with printing. First, we create a unique_lock which wraps control of the mutex. It ensures that no matter what non-terminating execution path our thread takes, it will release the thread if we leave scope. We then check our condition_variable. Using our unique_lock, if “goforit“ is true, then we continue to hold the lock and we know we can print. If “goforit” is false, we need to wait. Thus, we release the lock, the thread sleeps, and it waits to be notified.

This ends with our main thread joining the created threads ensuring we only terminate the whole program if the threads are done or more accurately, non-joinable.

This is an interesting way to approach a Hello World implementation. You get to see a little bit of threaded programming and the thinking that you need to ensure to coordinate your threads if they share as resource, in this case the output mechanism.

Let me know what you think or if you have any questions. Also let me know if you find any value here and if not I’m interested to find out. As always, the best way to learn programming is to put it into practice so what are you waiting for, get coding.

Wednesday, July 24, 2019

The Last “Hello World” You will need

Entering the world of C++

Saying Hello World in more ways than one

Hello World! In this post, I wanted to begin my exploration of c++ and beyond by first unwrapping
one of the most well written topics in computer programming. That is, I want to contribute to the
plethora of Hello World tutorials that exist out there. This time however, we are going to write Hello World in a number of different ways. If you can think of another way, go ahead and post it in the comment section below.

Here we assume that you have your C++ environment all together. If you don't here are some other
fine tutorials to get you fired up.
[linux], [windows], [mac]

The Bread and Butter

First we are going to write Hello World in whats considered the defacto way in modern C++.
If you are ever wondering how you should write your hello world program, this
should be your first choice. It looks like this.

There it is in all its glory. Looking at those lines of code is like seeing an old friend, you can’t help but say hello back. Breaking it down, the first line introduces the C++ standard input output file stream library. This makes the input and output facilities available in our program. Next line lets the compiler know that we are using the namespace ‘std’ throughout this source file. Without this line, we would have to add “std::” in front of all standard library members such as “std::cout” instead of just “cout” as you see later on in the code.

The next block of code is where the magic happens. “int main()” defines a function called main that returns an integer. In c++, main is a special function name. When running a C++ project, the computer (really the runtime) looks for a function named “main” as the starting point of execution. Following this, we then output “Hello World” to the console by using our “cout” function from the iostream standard library. We place the “endl” at the end to create a newline. 

We will talk about “endl” in more detail in the future.

The “return” produces the value that main will return once it runs this line. This main returns 0 as a result.

Nice, that's a complete Hello World for you. But lets see other ways we can achieve this program.

Hello World like it’s 1999

C++, getting its roots from C, also has some other functions that allow one to output to the console. These functions, born in C can be very useful as well. Let’s take a look once more at a Hello World program but this time we are going to say "Hello World" a number of times. Why? Just because we can.

I'm sure you are thinking “wait, what?”. But check this out. We import our library first, this time using the C-style input output library. Then we introduce our main function once again. This is followed by our second way of getting our text to console, the “printf()” function. In this instance, it completes the same job as that of our “cout” example. Resulting in “Hello World” being produced. The “\n” how a new line character is represented.

After this, we start getting into some interesting, yet onerous approaches to hello world. You probably won’t be writing the program like this but it does offer a deeper understanding into this function. After our first “printf” line, we use “printf” once again. This time we start with a string that has a ‘%s’. This uses printf’s formatting functionality which will replace‘%s’ with any string we provide. In this case the next argument which is our “Hello World\n”. This prints to the console what you would expect, replacing ‘%s’ with our hello world string.

The next two “printf”s once again utilize the string formatting offered by printf. In this case the ‘%c’ lets use replace it with a single ascii character. The third “printf”, places a series of ‘%c’, one for each character in “Hello World\n”. Note that ‘\n’ is treated as a single character. Following this formatted string, we have a comma separated list of each character to replace each ‘%c’ in this string as they appear. Thus replacing each ‘%c’ with the characters of “Hello World”. Up next we have a similar “printf” function with the same series of ‘%c’ but this time we represent each character as its equivalent digit. In C++ each char can be represented as an unsigned integer. Looking at an ASCII table you can see which integer corresponds to which character. Telling the function to look at those numbers as characters using the ‘%c’ we once again get our “Hello World”.

There you have it, “printf” in all its Hello World glory. But if you think we are done with our Back 2 the Future experience you can guess again. Let’s look at our third approach to Hello World.

Our third method of getting text to the terminal is using “puts” function call. This takes a c-style string as input and prints it to console. C-style means a char pointer to a null terminate sequence of characters. Above, I use two ways to create this c-style string. First we declare a const character pointer and assign it a string literal. In modern C++, you are required to declare a char pointer constant when assigning a string literal to it - one of the attempts made to make C++ safer with less pitfalls. Next, we declare an array of char’s and assign it the string. This creates an area with each character in each array cell.

We are breezing over a number of C++ concepts like arrays and pointers but we will cover those in the future so stay tuned.

We then pass those strings to the “puts” function which as you know outputs the string to the console. Like the comment says, the line starting from the “//” onward, “puts” adds a newline at the end of its output which is great for us. Looking at all the examples above, we can see all the main print to console functionality offered by C++ out of the box. As we mentioned before, your first instincts should be to reach for the std::cout function call. But these other two functions are available when the situation calls.

With these tools at hand, why not have a little fun. Let's write two more Hello World programs but let's spice things up a little more.

Sharing the Workload
These next examples bring in more complex topics into the picture. We will be touching on them briefly but it gives you an idea of some cool C++ libraries available.

Now, it's great having our main function do the work of printing to console. But, what if we want to get another execution thread to take care of this work for us? Why would we want to do that? There are many reasons that may perhaps exist. But for our hello world, we are doing it for the joy in seeing “parallel” code.

“What in the world is going on here” might be your thought. Let me explain, off the bat we use new standard library functionality, which is the std::thread api. This allows us to create a second thread of execution that can run separately from our main thread of execution. Think of this as hiring a new intern to work with you. Now you and the intern can work together at the same time.
Next we see some interesting syntax. "[]{...}", allows us to declare an anonymous function which is a function with no name. Remember, main() is our other function that we know of. The only line of code in our anonymous function is the Hello World as we have seen before. Together, this creates a new thread object and passes in, as input, the lines of instructions that the thread will begin to execute immediately once created.

The following line, is an if statement where we check whether our thread can be joined. In other words, we check if the thread has neither finished running nor been explicitly detached from our main thread. If the thread is joinable, we join our main thread to it. This makes our main thread wait until our second thread completes running before moving from that join point.
Again, some new concepts here but at the very least we have named some new topics to explore on our C++ journey.
What happens when we want to employ more than one thread in our Hello World experience. One might say, “we really should not”. I say, “more threads please!”. Let’s do it.

Yep, this is our most contrived example of a Hello World. Lots of cool concepts abound here. Our goal here is to have two new threads write "Hello World" one after the other. Considering these threads begin execution right after being created, we need to synchronize their activity. Here is where we introduce a mutex and a conditional_variable. Together they let us create checks and balances that must be met before a thread can execute code. We are going to walk this code in finer detail in a different post but for now, understand that the usage of the mutex library and the conditional_variable library allows us to coordinate the actions of our threads. Thus, allowing control of when thread one prints “Hello” and when thread two prints “World”.
What more detail, dive in here.

What a journey, we have seen how to use C++ standard library to print to the console and we even dipped our toes into the standard threads library to achieve the same thing. Alongside learning more about C++, its syntax and libraries, this is an example really about simple ways to play with a language and learn/practice something new. Hope you all find this useful and insightful. Let me know if there are any particular topics you are interested in me covering below. If you just have comments to share please do the same below.

What are you waiting for, get coding!

Sunday, March 31, 2019

A Welcome To All

In a time were the world is under constant disruption - from our ambitions to venture into space,
Distributed Ledger Technology and the financial system, Machine Learning impacting medicine,
logistics and transport, user experiences, and the development tailored shopping experiences and
more - these revolutions are spurring society faster and further into the future. But in this world of
change and turbulence, how do we sail our ships to find success as we navigate this wide open
landscape of success. This is a topic that I want to explore and it is here that this exploration will
occur.

Welcome to Rise.BlackUnicorn. Here, we are going to talk about emerging technologies with the
aim of getting ourselves ready to not stay abreast with the rising tides but to soar above them. Over the next few months, there are a few topics that I aim to discuss - from the intricate details of the upcoming C++20 release, getting us ready for a modern take on one of the most successful languages ever built, to understanding new approaches and technologies in a sector or two. I will also be discussing ways that you as path makers can navigate spaces and better understand where you are going as well as better ways to help get towards your goals. With these topics, and others down the road, you and I aim to understand what lies ahead and how we can use these emerging technology to our advantage.

My name is Theko Lekena, I am a Software Engineer at Axoni, a leading blockchain infrastructure
company playing a key role in equipping the financial industry with the right tools and infrastructure to succeed in a Blockchain world. But I seek to break down complexity thus uncover the unicorn within us all. As an engineer, what I have always found fascinating was the question of how one gets better at what they do, the craftsmanship. How does one spur their own personal growth and how can one ignite and foster better growth in others as a leader. To achieve this, I have opened my eyes and began to stretch my mind as I poured over new information and content. All in the attempt to better understand what it all means for me and the growth that I seek. I want to bring that insight here.

As we all take this journey, reach out to me and let me know what topics you would like us to explore or if you have any questions about some of the topics and posts we have up and lets Rise together.