Getting Started

“I want to become a web/mobile developer/designer. What can I do to get started?”

There are a variety of web and mobile bootcamps across the country. For just $5,200, Big Nerd Ranch promises to get you writing iOS applications in just seven days. It looks like you should probably arrive with some programming experience, but they’ll train you in the essentials in a week. Not sure you’re ready to learn mobile development in less than 168 hours (I assume they let you sleep at the ranch)?

Coding Dojo will give you 14 weeks to learn three separate development stacks – you might choose to learn backend development with Python, front-end JavaScript development, and iOS mobile development. That would allow you a lot of flexibility to contribute in several areas within a company. Tuition for the 14-week program ranges from roughly $10,000 to $14,000 depending on the location. They also offer career support to help you find that first job – “94% of our students who complete our career services program find a job within 180 days of graduation.”

I do not have any experience with coding bootcamps. They do seem to acknowledge that there is a lot of work involved, and sites like Coding Dojo do indicate that career development is a process – they don’t seem to believe miracles happen in 14 weeks. But what can someone do if they want to switch careers and become a software developer, but they’re not ready to go back to college for a 4-year Computer Science degree?

Here are a few suggestions…

Start Learning

This one’s rather obvious, but it involves more than learning to code. You want to gather some general information about the kind of work you think you might want to pursue. If you are more interested in the visual design aspects of web development, you will want to learn HTML and CSS. You can help establish the appearance and use interaction for a website without needing all the skills associated with web development. However, if you want to build web applications, there’s some programming involved – likely some JavaScript, Python, or Ruby. In either case, there’s an important step that involves learning something about yourself as well.

Web development is not for everyone. It requires some ability to take a problem and break it down into smaller parts. To be successful, you need to see where one problem is like another problem and might share the same solution. You need to think about problems in abstract ways. You need to reason through the logical steps involved in a task to bring it to completion. Now, no one is good at all of these things right away, but some people have no interest in becoming good at these things.

You can get a quick feel for your interest in coding by finding a brief tutorial online. The Mozilla Developer Network provides some very simple HTML, CSS and JavaScript tutorials. A lot of people are fine with HTML and CSS, but find that the jump into programming with JavaScript requires another level of thinking and commitment.

If you’re interested in mobile development, Apple and Google provide resources for getting started that will include some basic tutorials. If it’s your first exposure to programming, you might need to find some basic “learn to program” tutorials first. Sites like Coursera can be helpful here – just make sure you can find something that’s geared toward someone with no prior programming knowledge.

Once you’ve determined that you want to move forward, and you have some feel for what you want to learn, you can look for more advanced tutorials to help you get a firm grasp on your subject. Some people are fully capable of doing this on their own. Others benefit from the structure provided by courses at a local community college, development bootcamp, or online training (such as Lynda.com, Pluralsight, or CodeSchool). If you can find someone to guide you through the learning process and answer questions, you’ll definitely benefit from their knowledge. If it’s just you and the internet, you can succeed, but be prepared to learn some things incorrectly along the way. (The internet is full of information – both good and bad.)

Start Practicing

As soon as you feel like you have enough knowledge to do something, start putting that knowledge to practice. Build things and throw them away. If you see something interesting on the internet or in a mobile app, figure out how to mimic it. At some point, you will need to break away from copying the steps of a tutorial to actually putting some things together on your own. This is where you can determine how much you’ve really learned. You will undoubtedly struggle to copy a lot of the things you see, but think through how you can break it down into smaller ideas that you can copy.

For the aspiring web developer, if you’re short on ideas to use for practice, visit a site like CodePen and see what other people have built. Find something that looks like it would be at your level and try to recreate it. If you get stuck, you can see how it was initially done and learn the skill of understanding someone else’s code – and this is a crucial skill to learn.

If you’re interested in mobile development, find the simplest app in the App Store or Google Play Store and create your own version of it. You don’t need to publish it, but you will learn a lot during the process of trying to duplicate it.

Of course, if you already have ideas for something you want to build, start implementing them. If you’re trying to build something you want to use yourself, you’ll be much more motivated to get it working.

Start Networking

Meet as many other people as you can in the area of development you’re pursuing. Meetup may be a helpful site to find gatherings in your area where you can learn new ideas and network with other developers. Some meetups may even provide opportunities to work with others on community-based projects for local non-profits.

Local chapters of Code for America, such as Code for KC offer opportunities to work with other volunteers who are building tools to make local government better. Attend a meeting, introduce yourself to someone, and share your career goals. You may be able to find a group of people who are willing to help you learn while also gaining experience that you can share with prospective employers in the future. I would suggest you only work on a project where there’s some genuine interest. That interest will likely go a long way if you still needs a lot of help from other team members to complete a task.

Start Publishing

At some point you’re going to want to find a job, and you’re employer is going to want to know what you’ve done. If all you can do is tell how you’ve taken some classes or attended a bootcamp, you’re going to have a very hard up-hill battle. If you can link to web pages you built or mobile apps you’ve published, an employer can have some confidence your skills are legitimate, even if they are still in the early stages of their development.

One caution here. If you’re claiming that you were responsible for something, you should be able to explain how you built it. You should expect questions – lots of questions – about any work you’ve done. Why did you choose A over B? How does that animation work? Did you run into any problems building that?

Study, Study, Study

When it’s eventually time to go through the interview process, be extremely well prepared. Expect someone to ask you to write some code to do something as part of the interview. Expect them to show you code and ask you what it does. If they don’t drill you heavily on your knowledge, having the information ready will allow you to give much better answers than you would otherwise give.

If you’re not sure where to begin, go to Google or Bing and search for interview questions (web, iOS, Android). Make sure you can answer anything you see. If you know someone already in the kind of position you’d like to have, see what you can learn from them about a typical interview process.

Once you’ve identified a company, check Glassdoor’s interview postings for that company and similar companies. You may not receive the same questions, but you will get an idea of what to expect. If you can’t answer questions you see they are asking, you may want to hold off on trying to get an interview until you’re better prepared.

Make any interview a learning experience. You want to convince a company you’re ready to work, but you also want to come away from the interview experience knowing how you can improve for the next one. If you don’t take notes during the interview, write down everything you can immediately afterward (i.e. when you get back to your car). Make sure you’re ready to answer any of the interviewers questions the next time around.

Whether your self-taught or you’ve been bootcamped or you fall somewhere in between, don’t expect the process of becoming a web/mobile developer to be easy. Assume your three months of bootcamp training is going up against a developer with a year of work experience and be prepared to work hard enough to overcome that gap.

Related Articles:

How to land a top-notch tech internship — and a tech job — while you’re still in school
I spent 3 months applying to jobs after a coding bootcamp. Here’s what I learned.

What is Closure?

What is closure? If you’ve worked with languages like C and C++ before coming to JavaScript, it may be unexpected behavior. If you’re learning JavaScript as your first programming language, you may not even be aware it’s happening.

If we declare a global variable in JavaScript, it’s accessible from within any of the functions we define and lives as long as out program is running. If we declare a variable within a function, it’s only accessible from within that function and only lives until the function has finished executing.

var count = 0; // A global variable

function incrementCounter() {
    // We can access the global "count" variable
    // and the local "oldValue" variable in here.
    var oldValue = count;
    count++;
    console.log("Count bumped from " + oldValue +
                " to " + count);
    // Once we're done in here, "oldValue" goes away.
}

This behavior shouldn’t be surprising, but an example of closure might be. JavaScript allows us to define functions within other functions. We can even define functions within those functions within functions and so on. These nested functions are where we can run into instances of closure.

function Counter() {
    this.count = 0;

    this.increment = function () {
        this.count++;
    }
}

This is a simple constructor function for a Counter object where the increment function is intended to bump the value of the count variable. But there’s an alternate way to write this constructor function that may better serve its intended purpose. If someone tried to use this Counter object as follows, they will run into a problem.

var c = new Counter();
setInterval(c.increment, 1000);

The intention is obviously to increment the counter’s value every second, but can you see why this won’t work? If not, you may want to review this post on using this. Here’s an alternate implementation that will work with the setInterval example.

function Counter() {
    var count = 0;

    this.getCount = function () {
        return count;
    }

    this.increment = function () {
        count++;
    }
}

The object’s count property has been replaced by a local variable within the constructor function and we’re referencing that local variable from within the two nested functions. This is closure at work. JavaScript not only allows a function to access its own local variables, but it also allows a function to access any local variable declared within any other functions that enclose it. The getCount and increment functions can access their own local variables, any local variables defined in functions that contain them, and any global variables. One advantage of using closure with the count variable is that it removes the need to use this within the getCount and increment functions (so they are slightly easier to use as callback functions). Additionally, we are ensured that only functions defined within Counter can access the count variable. It is effectively hidden from any other functions, which means it cannot be mistakenly reset or decremented from outside Counter. (On the down-side, we can’t implement getCount and increment as prototype functions.)

Typically, we expect local variables to remain in scope until a function returns, then we expect them to go away. In many languages this is always the case, but it doesn’t always happen with JavaScript.

function IntervalCounter(seconds) {
    var count = 0;
    var milliseconds = seconds * 1000;

    function getCount() {
        return count;
    }

    setInterval(function () {
        count++;
    }, milliseconds);
}

This example defines two local variables for IntervalCounter: count and milliseconds. When IntervalCounter finishes executing, milliseconds goes out of scope and is no longer accessible. However, closure ensures that count will continue to be available to getCount and the setInterval callback function.

Closure provides an effective method of data protection in JavaScript, though it’s not without its own set of risks. If you are inexperienced with JavaScript, it is possible to reference local variables that hold large objects or arrays in memory. When these variables are then referenced within enclosed functions, you may accidentally consume large blocks of memory without knowing it. As with most programming tasks, you always want to consider carefully how your program is actually working and make sure you are acting responsibly with the programming language.

Working with Forms in Two Functions

Interacting with forms – it’s a common need in JavaScript apps. You need to gather information from the form when it’s submitted; you need to initialize a form when it’s first displayed to the user. Here’s a simple form:

<form id="user">
    <input type="text" name="first-name" />
    <input type="text" name="last-name" />
    <input type="submit" name="submit" value="Submit" />
</form>

One way to gather the information would be to retrieve each input value individually.

var elements = document.forms["user"].elements;
var firstName = elements["first-name"].value;
var lastName = elements["last-name"].value;

But that soon becomes tedious as the size of the form grows. What we really want is a function that will allow us to easily retrieve all the data from a form. Something that might be used like this:

var userData = readFormData("user");
var name = userData["first-name"] + " " +
           userData["last-name"];

In a single function call, we could have all the inputs gathered into a JavaScript object. We could also conceive of a function that would write the data from a JavaScript object back into the form.

writeFormData("user", userData);

So, how would we implement such functions?

function readFormData(formIdOrName) {
    var formData = {};
    var elements = document.forms[formIdOrName].elements;
    for (var index = 0; index < elements.length; ++index) {
        var name = elements[index].name;
        formData[name] = elements[index].value;
    }
    return formData;
}

function writeFormData(formIdOrName, formData) {
    var elements = document.forms[formIdOrName].elements;
    for (var index = 0; index < elements.length; ++index) {
        var name = elements[index].name;
        elements[index].value = formData[name];
    }
}

After calling readFormData, the userData object might look something like this:

userData = {
    "first-name": "John",
    "last-name": "Smith"
}

The name attributes from the form elements have been used as property names and the value properties from the form elements have been assigned to those property names. But what if we want to add a checkbox to the form – will our functions still work? Not yet. Checkbox inputs store their state in the element’s checked property instead of the value property, so we need to do a bit more work. A couple of additional functions will help us gather information from checkboxes, dropdown lists, etc..

function getElementData(element) {
    // Special handling for <select> elements
    if (element.tagName === "SELECT") {
        return getElementSelections(element);
    }
    // Special handling for checkboxes and radio buttons
    if ((element.type === "checkbox") ||
        (element.type === "radio")) {
        return element.checked;
    }
    return element.value;
}

function getElementSelections(element)
{
    // Look at all the <option> elements and return the
    // selected options.
    var values = [];
    for (var index = 0; index < element.options.length;
         ++index)
    {
       if (element.options[index].selected) {
           if (element.multiple) {
               // Multiple selections are returned in
               // an array.
               values.push(element.options[index].value);
           } else {
               // Single selections are just returned as
               // a string.
               return element.options[index].value;
           }
       }
    }
    return values;
}

function setElementData(element, data) {
    if (element.tagName === "SELECT") {
        return setElementSelections(element, data);
    }
    if ((element.type === "checkbox") ||
        (element.type === "radio")) {
        element.checked = data;
    }
    element.value = (data === undefined) ? "" : data;
}

function setElementSelections(element, data)
{
    // If the data isn't submitted as an array, we can
    // create an array of one element to simplify the
    // selection logic.
    if (!(data instanceof Array)) {
        data = [data];
    }
    for (var index = 0; index < element.options.length;
         ++index)
    {
      if(data.indexOf(element.options[index].value) >= 0) {
        element.options[index].selected = true;
      }
    }
}

Now, with a couple of tweaks to our read and write functions, we can easily transfer data between a form and a JavaScript object.

function readFormData(formIdOrName) {
    var formData = {};
    var elements = document.forms[formIdOrName].elements;
    for (var index = 0; index < elements.length; ++index) {
        var name = elements[index].name;
        formData[name] = getElementData(elements[index]);
    }
    return formData;
}

function writeFormData(formIdOrName, formData) {
    var elements = document.forms[formIdOrName].elements;
    for (var index = 0; index < elements.length; ++index) {
        var name = elements[index].name;
        setElementData(elements[index], formData[name]);
    }
}

Combined with JSON.parse, JSON.stringify, and some AJAX calls, readFormData and writeFormData can be used to easily send and receive form data between the browser and a web server. We can even package everything up into a nicely wrapped object to look something like this:

function FormData(formIdOrName) {
    this.form = document.forms[formIdOrName];
}

FormData.prototype.readData = function () {
  ...
}

FormData.prototype.writeData = function (data) {
  ...
}

var userFormData = new FormData("user");
var userData = userFormData.readData();

Hopefully, this will simplify some of your work with forms in JavaScript. You can experiment with the final sample code on CodePen.

The (Proto)Typical JavaScript Function

We’ve seen that constructor functions can be used to initialize JavaScript objects in a consistent manner. The constructor can be used to ensure that an object is always initialized with a known set of properties and default values for those properties. But it’s also possible to assign functions to object properties from within a constructor function.

function Neighbor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = function () {
        return this.firstName + " " + this.lastName;
    }
}

var friend = new Neighbor("Tom", "Smith");
var name = friend.fullName();

Assigning a function to the fullName property provides a convenient way to access a Neighbor's full name. However, using an anonymous function is an inefficient way to add this functionality. If I create another Neighbor instance, JavaScript will create another instance of this anonymous function.

var friend1 = new Neighbor("Tom", "Smith");
var name1 = friend1.fullName();

var friend2 = new Neighbor("Sally", "Jones");
var name2 = friend2.fullName();

The sample code runs as expected, but if we compare instances of the fullName property, we can see they do not reference the same function. Every time we execute our constructor function, JavaScript creates a new instance of the anonymous function and assigns it to the fullName property.

if (friend1.fullName !== friend2.fullName) {
    alert("The fullName properties are NOT identical.");
}

Creating one extra instance of this anonymous function may not be a big deal, but what if our object has a half-dozen functions and we have hundreds of Neighbor instances? Each instance needs to be created, which requires some amount of time and memory.

One solution would be to simply define a named function outside of our constructor function.

function Neighbor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = concatenateFullName;
}

function concatenateFullName() {
    return this.firstName + " " + this.lastName;
}

It may look a bit strange, but it does work. However, our function is no longer tightly coupled to the Neighbor object, which brings us to the JavaScript prototype function. All JavaScript objects have a prototype property that allows us to attach new properties, not just to an object instance, but to a specific object type. In this case, we can associate a fullName property with the Neighbor type.

function Neighbor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

Neighbor.prototype.fullName = function () {
    return this.firstName + " " + this.lastName;
}

Now, all objects created with the Neighbor constructor function will have an associated fullName property through Neighbor's prototype. If we create two Neighbor instances, they will share a common fullName function. When we reference friend.fullName, JavaScript will look for a fullName property on the friend object, but if it doesn’t exist, it will also look for a fullName property on the prototype of the Neighborconstructor function that was used to create the object.

if (friend1.fullName === friend2.fullName) {
    alert("The fullName properties are identical.");
}

Of course, prototype properties don’t have to reference functions. They can also be used to share values across object instances.

function Tank(level) {
    this.level = level;
}

function.prototype.alertLevel = 10;

function.prototype.isLevelSafe = function () {
    return this.level >= this.alertLevel;
}

var tank = new Tank(100);
var isSafe = tank.isLevelSafe(); // returns true
tank.level = 2;
isSafe = tank.isLevelSafe(); // returns false

Prototypes allow us to associate a single property instance with all instances of a particular object type, which gives us the ability to extend an object’s functionality beyond what’s simply provided within it’s constructor function.

Constructing Constructor Functions

When you are first learning JavaScript, you will be introduced to two ubiquitous language features: functions and objects. As you begin to experiment with creating objects, you may find is useful to implement a simple function to create commonly used object types. For instance, here’s a function that will create an instance of a photo object:

function createPhoto(url, date, caption) {
    return {
        url: url,
        date: date,
        caption: caption
    };
}

var photo = createPhoto("rabbits.jpg", "05/10/2015",
                       "Someone's been eating my radishes.");

Using such a function ensures that every photo object has the same set of properties, and this example provides an excellent starting point for understanding JavaScript constructor functions. What if we make a few minor changes…

function initPhoto(newPhoto, url, date, caption) {
    newPhoto.url = url,;
    newPhoto.date = date;
    newPhoto.caption = caption;
}

var photo = {};
initPhoto(photo, "rabbits.jpg", "05/10/2015",
          "Someone's been eating my radishes.");

Instead of creating the object within our function, we create the object and pass it to the function for initialization. But the end result is the same. We have a new object with all the expected properties attached. This is essentially how constructor functions work, but the syntax is slightly different.

function Photo(url, date, caption) {
    this.url = url;
    this.date = date;
    this.caption = caption;
}

var photo = new Photo("rabbits.jpg", "05/10/2015",
                      "Someone's been eating my radishes.");

When we use the new keyword, JavaScript creates a new object and passes it into the constructor function. However, instead of appearing in the function’s argument list, it’s accessed using the this keyword. By convention, constructor functions are capitalized to distinguish them from other functions.

Once you feel comfortable with how constructor functions are used to initialize new objects, you can begin to experiment with some of their other benefits – prototypes.

Two Quick Steps to JavaScript Events

If you’re just starting out with JavaScript and want to respond to an event on the page, you can keep these two simple steps in mind. For this example, we will look at responding to a click event on an anchor tag.

<a id="click-target" href="redirect.html">Click here.</a>

Including an id attribute will allow us to easily find the element within the page.

1. Listen for an event.

We first find the anchor tag, and begin listening for its click event. Listening is accomplished by calling the element’s addEventListener method and providing a callback function.

var anchor = document.getElementById("click-target");
anchor.addEventListener("click", handleClickEvent);

Or we can use the element’s onclick property to specify the event callback function.

var anchor = document.getElementById("click-target");
anchor.onclick = handleClickEvent;

2. Implement a callback function.

An event listener always receives an Event object that describes the event. For our example, we will receive this object as the first argument in the callback function, and reference it with the variable e.

function handleClickEvent(e) {
    // Respond to the click event.
    alert("Anchor was clicked!");

    // The default action when clicking an anchor tag is to
    // redirect the browser to the URL specified in the
    // href attribute. If we want to prevent the redirect,
    // we can use the Event object to prevent the default
    // behavior.
    e.preventDefault(); 
}

Four Quick Steps to C# Events

If you’ve ever found .NET events a bit confusing, here are four simple steps that will get anyone up and running.

1. Define the data our event will send.

Events will typically have some information associated with them. The .NET Framework provides an EventArgs class, which serves as the foundational class for all event data in the .NET Class Library. It’s recommended that we use it as the base class for event data when creating our own events.

class LocationChangedEventArgs : EventArgs
{
    public LocationChangedEventArgs(DateTime inTime, double inLatitude, double inLongitude)
    {
        mTime = inTime;
        mLatitude = inLatitude;
        mLongitude = inLongitude;
    }

    private double mLatitude;
    public double Latitude
    {
        get { return mLatitude; }
    }

    private double mLongitude;
    public double Longitude
    {
        get { return mLongitude; }
    }

    private DateTime mTime;
    public DateTime Time
    {
        get { return mTime; }
    }
}

If an event doesn’t pass any information, it can still be a good idea to derive an EventArgs-based class for the event. Putting it in place from the start makes it easy to add data to the event in the future without needing to refactor all the code that uses the event. Instead of refactoring, we can simply add members to our subclass of EventArgs.

2. Declare the event.

Now that we’ve defined the data being sent for our event, we need to declare the actual event. Event declarations are done using the event keyword followed by a delegate type and the event name. If we follow the Microsoft guidelines, we can specify our delegate type using the generic EventHandler<T> class. All we need to do is specify our EventArg-based class type for the EventHandler. (More will be said about delegates below.)

class TrackingBeacon
{
    public event EventHandler<LocationChangedEventArgs> LocationChanged;
}

3. Raise the event.

Once the event has been declared, we just need to “raise” the event by passing it parameters that match the delegate type. Using the generic EventHandler<T> class as the delegate type means that we will pass two parameters through our event, just like all the events within the .NET Framework. The first parameter will be an object that specifies the sender of the event. The second parameter will be an instance of our EventArgs-based class.

class TrackingBeacon
{
    public event EventHandler<LocationChangedEventArgs> LocationChanged;

    // If we raise the event from within a virtual method, a derived class
    // will be able to override our event behavior.  
    protected virtual void OnRaiseLocationChangedEvent(LocationChangedEventArgs e)
    {
        // We can work with a copy of the event in case we
        // gain or lose subscriptions while calling any
        // event handlers. 
        EventHandler<LocationChangedEventArgs> handler = LocationChanged;

        // The handler will be null if no event handlers
        // have been added.
        if (handler != null)
        {
            handler(this, e);
        }
    }

    // A method within our class can raise an event
    // by creating an instance of our EventArgs class
    // and calling our method to raise the event.
    public void UpdateLocation(double inLatitude, double inLongitude)
    {
        if ((mLatitude != inLatitude) || (mLongitude != inLongitude))
        {
            mLatitude = inLatitude;
            mLongitude = inLongitude;
            OnRaiseLocationChangedEvent(new LocationChangedEventArgs(DateTime.Now, mLatitude, mLongitude));
        }
    }
}

4. Subscribe to the event.

We accomplish subscription to an event by “adding” an event handler to an event. To complete our example, we will create a Monitor class that subscribes to the LocationChanged event of a TrackingBeacon.

class Monitor
{
    private TrackingBeacon mBeacon;

    public Monitor(TrackingBeacon inBeacon)
    {
        mBeacon = inBeacon;

        // Adding an event handler is accomplished through
        // the event's += operator.
        mBeacon.LocationChanged += HandleLocationChanged;
    }

    // The event handler will be called when the
    // TrackingBeacon raises the event.
    private void HandleLocationChanged(object sender, LocationChangedEventArgs e)
    {
        LogLocation(e.Time, e.Latitude, e.Longitude);
    }
}

And that’s it! Define. Declare. Raise. Suscribe. Now we have an event!

Delegates

Oh, yes. Aren’t we supposed to use the delegate keyword somewhere?

A delegate type is simply a data type that specifies what our event handling method will look like. Instead of using the EventHandler<T> type, we could have defined a delegate type as:

public delegate void LocationChangedEventHandler(object sender, LocationChangedEventArgs e);

Then we would have defined our event as:

public event LocationChangedEventHandler LocationChanged;

EventHandler<T> simply provides a small shortcut (assuming we want to follow the Microsoft guidelines for events). If we want to depart from those guidelines, creating our own delegate type is always an option. (It is also necessary when targeting a version of the .NET Framework that does not support Generics.)

new” Subscriptions

When we add a handler to an event, aren’t we supposed to use new to add an object to the event?

Initial versions of C# required us to add event handlers by explicitly wrapping the handler in a delegate object like so:

    mBeacon.LocationChanged += new LocationChangedEventHandler(HandleLocationChanged);

With the release of C# 2.0, we can simply add the method without creation of the delegate object and C# takes care of everything for us.

Additional Information:
Event Design (MSDN, Framework Design Guidelines)
Events (MSDN, C# Programming Guide)

Don’t Tie Your Threads in Knots

Chip n’ Dale: Out on a Limb (1950)

One thing to remember about threads: they’re never polite. Ever.

While animated chipmunks may graciously insist that the other go first, threads never move themselves out of the way for other threads. When threads contend for a single resource this is not a great concern, but occasionally a situation arises where multiple threads contend for simultaneous access to multiple resources.

For example, let’s suppose we have a thread that is dedicated to a simple task. It checks the speed of a motor every ten seconds and records it in a log file. Another thread manages its own simple task of taking a temperature reading every six seconds and slowing the motor down if the temperature is too high. When the temperature is too high, the second thread also records the temperature in the log file. Assuming we have two resources to share between the threads (access to the log file and the motor), we might implement a logMotorSpeed() function as follows:

void logMotorSpeed()
{
    // Lock log file.
    logFile.lock();

    // Lock motor access.
    motor.lock();

    // Read motor speed and write to log file.
    const int speed = motor.getSpeed();
    logFile.writeSpeed(speed);

    // Unlock motor access.
    motor.unlock();

    // Unlock log file.
    logFile.unlock();
}

The second thread might perform the following actions:

void throttleMotorSpeed(int maxTemp)
{
    // Lock motor access.
    motor.lock();

    // Read motor temperature and write to log file.
    const int temp = motor.getTemp();
    if (temp > maxTemp)
    {
        // Lock log file.
        logFile.lock();
        
        logFile.writeTemp(temp);

        // Unlock log file.
        logFile.unlock();

        // Reduce to half current speed.
        motor.setSpeed(motor.getSpeed() / 2);
    }

    // Unlock motor access.
    motor.unlock();
}

At first glance, it might appear that we’ve successfully shared our resources between the two threads, locking and unlocking logFile and motor in each function to prevent the two threads from interfering with one another. However, we will eventually tie them into a knot that stops execution of both threads. At some point the two threads will execute with the following results:

logMotorSpeed() throttleMotorSpeed()
Lock logFile access
Lock motor access
Wait for motor access
Check temp.
Temp. is too high
Wait for logFile access

And now we’re deadlocked. Each thread is holding a resource that’s needed by the other and they are both forced to wait until the other thread releases its resource (which can’t happen while it’s waiting). And threads don’t have sufficient manners to back out of the way and let the other go first.

There are a couple of solutions to the problem in this example. If a thread can avoid simultaneously locking multiple resources, it should do so. Neither thread actually needs to lock both resources simultaneously. They could have been implemented as:

void logMotorSpeed()
{
    // Read the motor speed.
    motor.lock();
    const int speed = motor.getSpeed();
    motor.unlock();

    // Write the speed to the log file.
    logFile.lock();
    logFile.writeSpeed(speed);
    logFile.unlock();
}

void throttleMotorSpeed(int maxTemp)
{
    // Read motor temperature.
    motor.lock();
    const int temp = motor.getTemp();
    motor.unlock();

    // Write to log file and slow down motor.
    if (temp > maxTemp)
    {
        logFile.lock();
        logFile.writeTemp(temp);
        logFile.unlock();

        motor.lock();
        motor.setSpeed(motor.getSpeed() / 2);
        motor.unlock();
    }
}

In addition to avoiding a deadlock, we’ve also reduced the duration of each resource lock, which potentially improves each thread’s performance. But there are occasionally situations where both resources must be locked simultaneously. For this reason, it’s important to maintain a consistent locking order on our resources. The following change will also avoid tying our threads in knots:

void logMotorSpeed()
{
    motor.lock();

    // Read the motor speed.
    const int speed = motor.getSpeed();

    // Write the speed to the log file.
    logFile.lock();
    logFile.writeSpeed(speed);
    logFile.unlock();

    motor.unlock();
}

Even though we’re locking access to logFile and motor simultaneously, since both functions lock logFile within the lock on motor, we won’t deadlock. It’s no longer possible for a thread to lock logFile unless it has already obtained the lock on motor. We just need to be sure that we maintain a consistent locking order whenever any threads require simultaneous locks on multiple resources. While this is rather trivial in our example, the ordering of resource locks can become obscured as applications grow in complexity. A simple function call may hide resource locks that tie our threads in knots when we least expect it.

A few simple principles to keep threads running smoothly:

  • Maintain resource locks only as long as they are absolutely necessary.
  • Avoid nested resource locks whenever possible.
  • Maintain a consistent locking order when resource locks must be nested.
  • Consider what resource locks might be hidden inside function calls.

When does static Object Initialization Occur?

When working with static or global variables in C or C++, we know the compiler allocates storage for them in the application’s data segment. However, when the variable is an instance of a C++ class, it must be initialized as well as allocated. While the C++ language specification explains when this initialization takes place, it is a rather simple matter to demonstrate the rules for clarity.

The following code listing comes from a Windows console program written with Microsoft Visual Studio. It contains several Tracker objects which will help us trace the initialization of static and automatic objects.

#include "stdafx.h"

#include <iostream>
#include <string>

// The tracker class will simply stream output to std::cout so
// we can watch the execution flow of our test program.
class Tracker
{
public:
    Tracker(const std::string& inName)
        : mName(inName)
    {
        std::cout << "create " << mName << "n";
    }

    ~Tracker()
    {
        std::cout << "destroy " << mName << "n";
    }

private:
    const std::string mName;
};

// We'll place static variables inside and around a namespace scope
// to see if scoping affects initialization order.

static Tracker t1("before namespace");

namespace test
{
    static Tracker t2("within namespace");

    void test()
    {
        // We'll also define a static variable within a function
        // to see when it gets initialized.
        static Tracker t3("within function");
    }
}

static Tracker t4("after namespace");

// Our main function will contain static and dynamic Tracker
// instances to see when they are initialized.

int _tmain(int argc, _TCHAR* argv[])
{
    std::cout << "enter mainn";

    Tracker m1("dynamic in main before test");

    static Tracker m2("static in main before test");

    test::test();

    Tracker m3("dynamic in main after test");

    static Tracker m4("static in main after test");

    std::cout << "exit mainn";

    return 0;
}

Here’s the output from our program:

create before namespace
create within namespace
create after namespace
enter main
create dynamic in main before test
create static in main before test
create within function
create dynamic in main after test
create static in main after test
exit main
destroy dynamic in main after test
destroy dynamic in main before test
destroy static in main after test
destroy within function
destroy static in main before test
destroy after namespace
destroy within namespace
destroy before namespace

So, what we can observe about static initialization?

  1. Local static objects are initialized when they are first used (m2 and m4).
  2. All local objects are initialized in the order they are used (m1, m2, m3, then m4).
  3. Namespaces don’t affect initialization order.
  4. Non-local static objects are initialized when your program starts (t1, t2, and t4).
  5. Non-local static objects are initialized in the order they are declared within a file (t1, t2, then t4).

Again, this is all explained in the C++ Standards documents, but sometimes running simple test code is easier than parsing the standards. There’s one thing we did not try to observe here: when are static objects in one source file initialized relative to static objects in another source file? If you run some tests, you may see consistent results, but don’t depend on them. The exact behavior will vary between compilers as object files are linked together. There’s no simple way to guarantee the order in which these objects across multiple files will be initialized. We only know that objects within a file will be initialized in the order in which they are declared.

Back to the initialization of locally scoped static objects…exactly how does the compiler handle this lazy form of initialization? Let’s look at the disassembled code from test::test(). I’ve trimmed out some of the listing for brevity and added comments to explain how things work:

    void test()
    {
        // I've removed the entry code.

        static Tracker t3("within function");

        // Check the initialization flag on the t3 object. If it's
        // already initialized, we can skip it (jne to 0B1597h will
        // leave the method since there's nothing else in here).
000B151D  mov         eax,dword ptr [$S1 (0BC1ACh)] 
000B1522  and         eax,1 
000B1525  jne         test::test+0B7h (0B1597h) 

        // Set the initialization flag so we don't re-initialize the
        // next time we come through here.
000B1527  mov         eax,dword ptr [$S1 (0BC1ACh)] 
000B152C  or          eax,1 
000B152F  mov         dword ptr [$S1 (0BC1ACh)],eax 

        // Perform initialization by calling the class constructor.
000B1534  mov         dword ptr [ebp-4],0 
000B153B  mov         esi,esp 
000B153D  push        offset string "within function" (0B9910h) 
000B1542  lea         ecx,[ebp-0F0h] 
000B1548  call        dword ptr [__imp_std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string<char,std::char_traits<char>,std::allocator<char> > (0BD304h)] 
000B154E  cmp         esi,esp 
000B1550  call        @ILT+425(__RTC_CheckEsp) (0B11AEh) 
000B1555  mov         byte ptr [ebp-4],1 
000B1559  lea         eax,[ebp-0F0h] 
000B155F  push        eax  
000B1560  mov         ecx,offset t3 (0BC18Ch) 
000B1565  call        Tracker::Tracker (0B1073h) 

        // I've removed some clean-up code.
    }
000B1597  mov         ecx,dword ptr [ebp-0Ch] 
000B159A  mov         dword ptr fs:[0],ecx 
000B15A1  pop         ecx  
000B15A2  pop         edi  
000B15A3  pop         esi  
000B15A4  pop         ebx  
000B15A5  add         esp,0F4h 
000B15AB  cmp         ebp,esp 
000B15AD  call        @ILT+425(__RTC_CheckEsp) (0B11AEh) 
000B15B2  mov         esp,ebp 
000B15B4  pop         ebp  
000B15B5  ret              

One potentially important thing worth noting about the lazy initialization of locally scoped static variables: the initialization is not thread-safe! You can see there’s a small window between reading the initialization flag (at address 000B151D) and updating the initialization flag (at address 000B152F). If you don’t protect the initialization with a locking mechanism, the object may be initialized more than once (and debugging any problems may prove difficult if you’re not aware of how static initialization occurs). One way to avoid this problem would be to move the declaration so it is static within the file or namespace, ensuring it is initialized only on the application’s main thread at startup. However, this does make the object accessible from outside the method that uses it, which may or may not be desirable.