Threads using C++11 in 5 Minutes

Threads are seen as scary and strange. If used incorrectly, they can be frustrating and appear inconsistent. The good news is that C++11 has a great threading model and still links with useful libraries so you can get work done.

Minimum to Use std::thread

To use threads, you must know a little bit about how function pointers work in C++, because function pointers are how you specify the work to do in the thread. These function pointers specify what is known as the work function. At a minimum, your program also needs:
[table-wrap bordered="true" striped="true"]

What Why
#include Class declaration
void workFunc(); Declaration of thread work function
std::thread t1(&workFunc); Thread instance
t1.join(); Wait for thread to finish and clean up
[/table-wrap]

Starting Threads with “Regular” Functions

Function pointers for “regular” functions, also known as file-scope functions, work pretty much like you’d expect: take the address of the function name and then provide the arguments like you would if calling the function.

Note that you can also get by without explicitly taking the address, like std::thread t1(printHello,name);. This also works for static member functions, but it does not work with (non-static) member functions. So, for consistency, we will take the addresses of all work functions.

Starting Threads with Static Member Functions

In both the case of a file scope function and a static member function, the function pointer does not depend on a class instance. Given the semantic similarity of file scope functions and static member functions, they (unsurprisingly) use similar syntax when specifying a thread work function.

Launching a Thread with a Member Function

Member functions are fundamentally different from file scope and static member functions because member functions access member data in a particular instance of a class. Member function pointers are a different type from pointers to file scope functions and static member functions. They are usually larger, sometimes much larger. It is not uncommon for a member function pointer to be twice the size of a file scope function pointer. This is because the member function pointer must store both a function pointer and a pointer to the member data associated with the instance.

Whenever you invoke a member function pointer, the first argument must be an instance pointer of the appropriate type.

Putting It All Together

Here, we show the whole program followed by its output. The above fragments do not compile.

Wrap-up

There is likely less complexity involved than you expected when using threads. Things do get more involved when data structures are shared, but by using RAII along with destructors to handle “atypical” situations, C++11 threads are remarkably usable.

Learning Web Programing in 2014

Give me just a second while I get comfortable in my rocking chair. Ahh, there we go. So, you want to learn to program the Web?

  • Create a real project on which to learn.
  • Write requirements for the project before you start.
  • Do the project on something you care about.
  • Learn to use the developer tools built into the browsers.
  • Use forums to research issues and ask questions.
  • Setup an VM running Linux to host your project.
  • Pick a good editor and learn it.
  • Use validators
  • Have fun!

When I learned to program the web, your only real choice was Apache with Perl CGI or ISS with Visual Basic. SQL databases were generally too heavy and slow for web use, but we sometimes used them anyway. While MySQL existed by the late-90s, it wasn’t well known. PostgreSQL has been around for ages, but it was not an easy install and took more system resources than most web servers had to spare. I lived entirely in the UNIX/Linux world then and Berkeley DB was what we used. (Interestingly, Berkeley DB has more in common with the now-hip MongoDB and NoSQL than with MySQL, MS SQL, or Oracle).

For me, the only way to really learn something is to set a task and make it work. When I just work through tutorials I don’t run into the problems, the how-do-I-do-that? questions that pop-up with a real project.

For example, I needed one of my testers to become more familiar with HTML5 and CSS. She didn’t need to be a full-on programmer, but understanding what she was testing would (and did) give her better insight on how to test it and what kinds of problems to look for.

So for her first week on the job, her assignment was to create a website on orchids, which she grows. She ended up using tables to lay out each page, using hover tags to enlarge flower pictures, and using jQuery to make the section on each species expand when clicked. Make certain to look into jQuery, even as you start to learn JavaScript – it can make the seemingly impossible easy. It’s the sugar and cream for JavaScript.

(Oh, make sure you know that JavaScript has nothing to do with Java. They are entirely different languages. Client-side Java is essentially dead – too insecure, too annoying to update. JavaScript was never meant to hang around, it was a placeholder language created by Netscape to be replaced by Java when ready. That is why Netscape license the “Java” name to call it JavaScript. )

I suggest you do something similar to the orchid site. Find something you care about: Corvettes, dining out, hunting, scrimshaw… something and write down the requirements for your site before you start. Otherwise you’ll be tempted to “oh, we don’t need that” when you run into something difficult. You do not get to walk away from the tough problems on real projects. Getting the requirements correct is about 50% of the job. I put this cartoon up on my office door and within the month more than half of the engineers had a copy in the cubes.

what_the_customer_really_wanted

Write requirements as user stories. For example, if I were making a website about Corvettes:

  • The user can view the site without logging in.
  • The user can optionally create a login. With a login, the last page the user visited is recorded.
  • If the user logs into the site, he is taken to the last page visited.
  • The user sees a carousel of Corvette models on the landing page.
  • From the landing page, the user may enter their user ID and password to login.
  • From the landing page, the user can select a Corvette generation (C4, C5, C6, C7) to see info specific to that generation.
  • The user views generation and model specific information to include HP, torque, top speed.

Google is your friend. Let me repeat that, whenever I program I have many browser windows open, almost all from Google results. Use Chrome and install the Tab Cloud extension. It is an EXCELLENT way to save the state of the 25 windows I have open at the end of the day.

When doing web development, I always use two browsers: one for my references and one for debugging. I use Google Chrome and Firefox. They both have excellent developer tools built in. View the source for any page with Ctrl-U. Some pages have unreadable source while others are clear.

In Chrome, use the Developer Tools – Ctrl-Shift-I. Add FireBug to Firefox and use it. For JavaScript, make copious use of console.dir() and console.log() . These tools are powerful and flexible. You can use them at the surface level without any training. It is worth learning to use their more powerful features – they can save you huge amounts of time. YouTube has good videos on how to use the developer tools in Firefox and Chrome.

Don’t forget to use forums to ask questions, e.g. stackoverflow.com. Explain your problem clearly and concisely. Include example code, along with the actual output versus the expected output. If you want help, you are expected to do your own research before posting, both with Google searches and searching that particular forum. Summarize what you have researched and why it wasn’t acceptable. Include URL references.

I_will_use_google_bart

Host your project on a Linux server, preferably Ubuntu or CentOS. The easiest thing to do is us VMware Workstation or VirtualBox. This will give you an introduction to Linux, and while much of the web infrastructure will run on Windows, it runs best on Linux. By using Linux you won’t have the strange errors that after two days of Googling you find out is because Windows does that just a little different than Linux.

Find an editor you like, one with code highlighting. Notepad++ is dead-simple to use on Windows and does a great job; it is always one of my first installs on Windows. Visual Studio with a PHP plug-in does an excellent job for Windows but can be overwhelming. However, learning to use Visual Studio gives you a strong basis for other languages, including the very popular (and remunerative) .NET. On Linux, you will have to learn a text editor. nano is the easiest to learn, but it is pretty weak. Learning vi is a pain, but EVERY UNIX/Linux box you ever encounter will have vi installed.

Enable all warnings and use validators. They can save you a tremendous amount of time looking for a bug that happens to be a typo or a common mistake.

Most important, have fun! There is such an amazingly broad world that opens up to you once you learn to program.

Restructuring the Site

Newspaper vs. Encyclopedia

Something Old

The material I have posted to this blog falls generally can be classified as “timely” or “reference.” Looking at the articles, I see too many reference-type articles in the blog which is essentially “timely.” That is, much of what I have posted to the blog, which is like a newspaper, more properly belongs in an encyclopedia format. I noticed this partially due to having to dig back through old articles I wrote to find the reference material that I wanted.

OK, many of you are saying, “Duh!”. I had other priorities and merely having an outlet to share ideas and projects on the ‘Net was initially enough. Now I am looking to make the site both more useful and more active.

Something New

The revised site will have at least the following sections:

  1. Blog
  2. Wiki
  3. Better cross-links with advancedcplusplus.com
  4. Links to contextually relevant YouTube videos
  5. Topical Recommended Reading
  6. Access to Version Controlled Software

Already, wiki.branchpoint.net is active and the blog has moved to blog.branchpoint.net. Right now the home page redirects to the Blog. I’m going to create a landing page that looks better and pulls everything together. That includes advancedcplusplus.com and the corresponding YouTube Channels.

That’s where we are. The “Under Construction” front page on web sites has always bothered me; to me, a web site should always be under construction. So there won’t be an under-construction page, but please bear with me as I undertake making the site more useful to me and to my visitors.

Updating PHP on CentOS 6.3

Despite the fact that this references i386 when installing the repository, the subsequent package updates work for x86_64.

Understanding Sync Layers in YUI

A Sync Layer is an interface where the widget, e.g. {javascript}DataTable{/javascript}, is populated, updated from, and updates a data store. In our case, the data store is a RESTful interface using JSON.

To implement YUI Sync Layers, we use a {javascript}ModelList{/javascript} composed of Models. To understand Models, we go back to the basics and look at {javascript}Attributes{/javascript}.

{javascript}Attribute{/javascript} implements getter/setter functionality for a class attribute, which is called member data in C++. {javascript}Attribute{/javascript} is normally not used directly. Rather, implementations extend {javascript}Base{/javascript} which incorporates {javascript}Attribute{/javascript}, handles attribute setup, and adds lazy initialization to all attributes, improving performance.

Setting Up EC2 Web Server

Getting X11 Forwarding Working

It can be confusing to see the report {code}WARNING! The remote SSH server rejected X11 forwarding request.{/code}. You’ve made sure that {bash}/etc/ssh/sshd_config{/bash} has X11 forwarding enabled and that a local X Server is running. The problem is that many servers do not have {bash}xauth{/bash} installed by default. Adding this enables X11 forwarding.

LAMP

Firewall

Before connecting to the web server, you will need to allow HTTP to pass through the firewall. The easiest way is to use {bash}system-config-firewall{/bash}. As I frequently have difficulty getting the text versions of the {bash}system-config-*{/bash} to run, I use the graphical version.

MySQL

After setting up MySQL, you need to add a database:

PHP

Before the PHP installation will work, you need to enable some package repositories that are disabled by default. This is needed because {bash}php-mcrypt{/bash} is not available in the repositories enabled by default.

Miscellaneous

You need to “activate” the EPEL repository before installing phpMyAdmin, which can be found at {bash}/etc/yum.repos.d/epel.repo{/bash}.

Quick ‘n Easy LAMP Install on Red Hat/CentOS
Virtual Host Example Configurations
An In-Depth Discussion of Virtual Host Matching
Running Apache2 hosts as different users
Run Apache2 Virtual Hosts as Different Users

Setting up HTTPS

Self-Signing a Certificate for SSL
Generating the Keys
Apache SSL on Red Hat

Allow Access to a Directory Only Via SSH
Password Protect Directories with Basic Authenication