2/7/10

10 Useful WordPress Security Tweaks

Security has always been a hot topic. Offline, people buy wired homes, car alarms and gadgets to bring their security to the max. Online, security is important, too, especially for people who make a living from websites and blogs. In this article, we’ll show you some useful tweaks to protect your WordPress-powered blog.

1. Prevent Unnecessary Info From Being Displayed

The problem
When you fail to log into a WordPress blog, the CMS displays some info telling you what went wrong. This is good if you’ve forgotten your password, but it might also be good for people who want to hack your blog. So, why not prevent WordPress from displaying error messages on failed log-ins?

The solution
To remove log-in error messages, simply open your theme’s functions.php file, and paste the following code:

1add_filter('login_errors',create_function('$a', "return null;"));

Save the file, and see for yourself: no more messages are displayed if you fail to log in.

Please note that there are several functions.php files. Be sure to change the one in your wp-content directory.

Code explanation
With this code, we’ve added a simple hook to overwrite the login_errors() function. Because the custom function that we created returns only null, the message displayed will be a blank string.

Source

2. Force SSL Usage

The problem
If you worry about your data being intercepted, then you could definitely use SSL. In case you don’t know what it is, SSL is a cryptographic protocol that secures communications over networks such as the Internet.

Did you know that forcing WordPress to use SSL is possible? Not all hosting services allow you to use SSL, but if you’re hosted on Wp WebHost or HostGator, then SSL is enabled.

The solution
Once you’ve checked that your Web server can handle SSL, simply open your wp-config.php file (located at the root of your WordPress installation), and paste the following:

1define('FORCE_SSL_ADMIN', true);

Save the file, and you’re done!

Code explanation
Nothing hard here. WordPress uses a lot of constants to configure the software. In this case, we have simply defined the FORCE_SSL_ADMIN constant and set its value to true. This results in WordPress using SSL.

Source

3. Use .htaccess To Protect The wp-config File

The problem
As a WordPress user, you probably know how important the wp-config.php file is. This file contains all of the information required to access your precious database: username, password, server name and so on. Protecting the wp-config.php file is critical, so how about exploiting the power of Apache to this end?

The solution
The .htaccess file is located at the root your WordPress installation. After creating a back-up of it (it’s such a critical file that we should always have a safe copy), open it up, and paste the following code:

1
2order allow,deny
3deny from all
4

Code explanation
.htaccess files are powerful and one of the best tools to prevent unwanted access to your files. In this code, we have simply created a rule that prevents any access to the wp-admin.php file, thus ensuring that no evil bots can access it.

Source

4. Blacklist Undesired Users And Bots

Sm4 in 10 Useful WordPress Security Tweaks

The problem
This is as true online as it is in real life: someone who pesters you today will probably pester you again tomorrow. Have you noticed how many spam bots return to your blog 10 times a day to post their annoying comments? The solution to this problem is quite simple: forbid them access to your blog.

The solution
Paste the following code in your .htaccess file, located at the root of your WordPress installation. As I said, always back up the .htaccess file before editing it. Also, don’t forget to change 123.456.789 to the IP address you want to ban.

1
2order allow,deny
3allow from all
4deny from 123.456.789
5

Code explanation
Apache is powerful and can easily be used to ban undesirable people and bots from your website. With this code, we’re telling Apache that everyone is allowed to visit our blog except the person with the IP address 123.456.789.

To ban more people, simply repeat line 4 of this code on a new line, using another IP address, as shown below:

1
2order allow,deny
3allow from all
4deny from 123.456.789
5deny from 93.121.788
6deny from 223.956.789
7deny from 128.456.780
8

Source

5. Protect Your WordPress Blog From Script Injections

The problem
Protecting dynamic websites is especially important. Most developers always protect their GET and POST requests, but sometimes this is not enough. We should also protect our blog against script injections and any attempt to modify the PHP GLOBALS and _REQUEST variables.

The solution
The following code blocks script injections and any attempts to modify the PHP GLOBALS and _REQUEST variables. Paste it in your .htaccess file (located in the root of your WordPress installation). Make sure to always back up the .htaccess file before modifying it.

1Options +FollowSymLinks
2RewriteEngine On
3RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
4RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
5RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
6RewriteRule ^(.*)$ index.php [F,L]

Code explanation
Using the power of the .htaccess file, we can check requests. What we’ve done here is ch

eck whether the request contains a

Sphere: Related Content

7 Personality Types of Developers Today

Developers and programmers are meticulous individuals, and developers sometimes stand out even among themselves.

We introduced you to 7 types of designers in our article 7 Personality Types of Designers Today. Developers have peculiar traits and habits of their own. This article looks at 7 types of developers today and their defining characteristics.

“The best programmers are not marginally better than merely good ones. They are an order of magnitude better, measured by whatever standard: conceptual creativity, speed, ingenuity of design or problem-solving ability.”
—Randall E. Stross

Stereotyping is generally not good practice. But we’re not trying to squeeze individuals into categories. Rather, delineating these types can help you figure out where you stand and help you understand others.

1. The Self-Help Constructor
The self-help constructor does whatever it takes to get the job done with his experience and skill, no matter how limited.

For example, he may accomplish the job by finding open-source software and other free applications and tools. His best assets are his willingness to learn what he needs to complete the job and his ability to absorb the information like a sponge. He is resourceful, working with whatever is available to him.

Not every client will be impressed. Those who don’t know any better will praise his work, but the self-help constructor does not develop applications or plug-ins himself.

He merely exploits existing tools to construct something seemingly new for clients. With the wide range of sophisticated tools available today, this is becoming easier, but much less impressive.

2. The Experienced Old Man
He may not be the hippest guy in this energetic and creative field, but the experienced old man brings something valuable to the table: a wealth of knowledge and experience.

He may appear outdated, unable to keep up with the latest tools and technology, but he is wise and knows the basics like the back of his hand.

His battle stories of bygone days will fascinate and thrill. He may not be the fastest or most technologically savvy, but slow and steady wins the race, and he delivers the goods as he always has.

He proves that the old-school style of coding may be antique but isn’t extinct. He may not be your heaviest hitter, but in times of great need, you know you can count on the experienced old man to deliver.

3. The Hardcore Geek
Workaholic doesn’t begin to describe the hardcore geek, this martyr of developers. He goes beyond the call of duty to deliver the product and takes great pride in his work.

He spends his lunch hour at his desk working frantically to finish the project ahead of time. When he allows himself a little free time, he reads books, journal articles and the like to improve himself. Very much an introvert, he feels most comfortable in the world of code and programming jargon.

The more code the hardcore geek writes, the more content he feels. As great as he is with code, he makes for a much better worker bee than a leader.

4. The Scholarly Know-It-All
The scholarly know-it-all is a walking encyclopedia on programming. He can spend hours passionately discussing the history of a programming language or dissecting imperfect code.

He is the poet of the programming world, whose code is a work of art that can be appreciated and analyzed. Recursion is his middle name, and he tweaks every block of code to perfection, regardless of timelines or readability.

He sets high standards for himself, and his work sometimes complicates matters: a task that should take only an hour to complete takes him a few months. Mind you, he’s not incompetent. On the contrary, he is highly capable; but he makes work for himself by creating new tools and libraries and even reconstructing entirely new systems, all to meet his own standards.

He feels obliged to impart his knowledge to others and share his passion for the theory and technical intricacies of coding and programming. He tries his best to explain to clients why using state-of-the-art technology is so important. Every project is his precious child.

The scholarly know-it-all is great to have on your team, but be sure you can get him to spend his energy on the important details, rather than waste time satisfying his urge to delve into every nook and cranny.

5. The Ninja
The ninja is a man of few words and keeps to himself. While similar to the hardcore geek, he has more in his life than code and work.

He is an enigma: not outright friendly or forthcoming, but he works surprisingly well on a team. Everyone notices his tireless nature but can’t figure out how he does everything so well and so quickly. There is much evidence of his work but little evidence that he did it. “Show don’t tell” describes his modus operandi best.

Never outwardly frazzled (try as you might to throw him off), he resolves problems quickly and efficiently, regardless of time or place. The ninja’s stealth sends chills down your spine, and he leaves you wondering how he managed to accomplish his feat.

A lone ranger, he gets the job done regardless of his status on the team or his relationship with other members. His motto? Don’t have doubts; just resolve the problem quickly and efficiently. This no-nonsense attitude makes him an absolute joy to work with.

6. The Clever Ambassador
The clever ambassador is the face of the team. He is outspoken and the unofficial project manager. His knowledge of software development, project workflows and code theory is adequate, but he does very little of the actual programming or work.

He is quick to pick up leads and great at communicating with clients. He is the consummate ring-master, able to please both clients (the ferocious lions) and team members (the elephants that could easily trample him if they wanted).

In his supervisory role, the clever ambassador ensures that every project meets the requirements and satisfies the client. He is the go-between, representing the development team for the client and balancing client satisfaction with practicality.

Having to walk this tight rope, he often feels that he should be better compensated, despite never doing any heavy lifting (i.e. coding). He is the model who sits pretty in front of the camera selling the product, while the rest of the team (make-up artists, hair stylists, etc.) works behind the scenes, receiving lower payment for what amounts to the same work.

7. The Half-Cup Speedster
The half-cup speedster takes on multiple projects at once. He works much faster than most, but his amazing quantity is tarnished by its quality: his speed results from cutting corners and hacking core.

He feels that optimizing and checking code takes too long. His code is messy because he does not follow best practices and never makes use of object-oriented programming (OOP).

Amazingly, despite his code looking like a minefield, the product works just as intended. Cutting corners is generally not good practice, but in an impossible crunch, the half-cup speedster might be the person for the job.

Unfortunately, much like the handwriting of physicians, his code is practically indecipherable. Should someone need to fix a problem that surfaces later, they will surely encounter difficulties. You can’t fix what you can’t read or understand.


Written exclusively for Webdesigner Depot by Aidan Huang, a freelance front-end developer and designer. He is also an editor at Onextrapixel.

As we’ve seen, there are many types of developers in the field. Which do you most closely resemble? Have you met anyone who fits any of the categories mentioned here? Share your thoughts with us in the comments below… Sphere: Related Content

How to Rescue Files from Dying External Hard Drive

Ram asks:
My WD external USB self-powered 500 GB hard drive just kicked the bucket. The drive is recognized after I plug it in, but the files are inaccessible and Explorer (or any other process) that tries to access it hangs. Disk scan with HDDTune shows bad sectors across the board.

Is there any way to salvage the files? I have tried to copy through Windows Explorer and a raw copy, but like I said above, all software hangs.

Thanks!

John said:
Get a copy of spinrite from http://www.grc.com It will likely restore the drive so you can copy the files. It is an amazing product it may work at it for hours but in most cases it will restore the drive but be ready to copy the files don't be fooled that it is fixed because if it rashes again its likely gone for good. If spinrite can't fix it nothing can.

Jessica said:
Perhaps you could try an Ubuntu Live CD?

1. Just download and put the .iso file to a USB flash drive using UNetbootin (which makes it really easy but just make sure to select your USB flash drive and not your current or external hard drive) or burn the .iso file on a CD.

2. Once you've done either, now plug in the USB flash drive w/Ubuntu or the CD you burned.

3. Reboot and assuming your computer can boot from USB or CD, choose "Try Ubuntu without any changes to your computer" when you eventually get to the screen with the orange Ubuntu logo.

If your computer doesn't boot from USB or CD, which means you go straight to Windows, follow the directions here to change the boot order in your BIOS (but first, just try to note the default boot order so you can revert this later on.)

4. When you get to the desktop in Ubuntu, plug your dying 500GB hard drive in.

5. You should now see your hard drive appear on the desktop as a mounted drive. Double-click on it to see if you can access your files and copy them to another place like your USB flash drive. Hope you can!

Even if this doesn't work, you might want to change your BIOS boot order back to the default settings.

Did this help?


Artur said:

If step 5 of Jessicas' walkthrough won't help with recovering data your next best bet is byte-by-byte copy of affected disk or partition.

Make sure that you have enough free space on target drive, login as root and type in:

# download ddrescue
wget http://download.savannah.gnu.org/releases/ddres...
# extract the source code
tar xjf ddrescue-1.8.tar.bz2
# compile ddrescue
cd ddrescue-1.8
./configure && make
# first, grab most of the error-free areas in a hurry:
./ddrescue -n /dev/old_disk /dev/new_disk rescued.log
# then try to recover as much of the dicy areas as possible:
./ddrescue -r 1 /dev/old_disk /dev/new_disk rescued.log

You can write to file if that's what you desire:

./ddrescue -r 1 /dev/old_disk imagefile.hdd rescued.log

Good luck with your data recovery. Sphere: Related Content

7/6/10

The Road Ahead for UML

By Ivar Jacobson and Steve Cook, May 12, 2010

UML comes of age -- but now what?

Ivar Jacobson is founder and CTO of Ivar Jacobson International and co-developer of UML. Steve Cook is a software architect at Microsoft and represents Microsoft at the OMG.
--------------------------------------------------------------------------------
More than 12 years have passed since the Unified Modeling Language (UML), became a standard. During these years opinions of UML have varied between delight and distaste. In this article, we discuss the deficiencies of the current UML specification and propose how to make it agile, leaner, smarter, and more flexible -- in short, how to prepare it for the future so that users can be confident that their investments in UML today will increase in value going forward.

At the beginning of the '90s there were 26 published methods on object-orientation, most with its own notation with its own set of icons. It was in this environment that UML was born. Although Grady Booch, Jim Rumbaugh, and Ivar Jacobson initiated the design of what became UML, many other contributors (including Steve Cook) quickly joined the effort and the Object Management Group (OMG) launched the result. UML quickly made most other methods -- along with their own notations, obsolete -- UML eventually became the standard we had hoped for, and toolbuilders and practitioners rapidly adopted the new approach.

Since UML first had outstanding success, we all knew that the pendulum would swing in the opposite direction some day -- and we were right. After a few years the setback arrived, but admittably for good reasons. For instance, at the outset there weren't many good UML tools. Some were very advanced, but hard to use. That disappointed many users and hindered the wide adoption of UML. The language received criticism from the academic world; for example David Parnas nicknamed it the "Undefined Modeling Language". The criticism was exaggerated, but not unfounded. Likewise, the original leaders of the agile movement were negative to modeling. They said "no modeling -- just code". Many people were skeptical about the tools, so they worked more with UML sketches on the whiteboard than formally with the tools themselves.

However, the pendulum is now swinging back. The tools have become better. Criticism from academics has mostly stopped. Agility has come to big companies and modeling is agile if done sensibly (and not as a "silver bullet"). Microsoft, for instance, has implemented UML in Visual Studio 2010, alongside domain-specific languages. Other important standards such as SysML are implemented as extensions to UML.

Thus it seems that today the world looks upon UML with a more balanced view. UML is not the panacea that it was sometimes sold as 10 years ago. Nor is it as bad as some academics, agilistas, and competitors have claimed. It is a practical tool to raise the level of abstraction of software from code to system level. Many organizations claim benefits from their use of UML, ranging from improved communication among developers to productivity gains using code generation from UML models.

UML is a good language to describe software systems at a higher level than code. Properly used UML can improve productivity and quality. After several years of consolidation, the OMG (the owner of the UML) is taking the initiative to improve it, having issued a Request for Information (RIF) on the Future Development of UML in 2009 under the leadership of Steve Cook.

The results of this RFI showed that users and vendors want UML to be leaner, more expressive, easier to learn, easier to integrate with other modeling and programming languages, and more relevant to today’s technologies. For example, some users want to use UML to drive the interactive behavior of a mobile application. Others want to use UML diagrams to automatically visualize the structure and dependencies within a massive distributed service-oriented application. Some would like models to be deeply integrated with modern programming languages without any semantic conflicts. Increasingly, users would like to use UML to model applications deployed in the Cloud. To address these needs, the OMG and UML vendors are working together towards making UML smarter and more agile.

Size and Complexity
One of the biggest complaints about UML is that it is too large and too complex. Typically a project that uses UML only uses 20% of the specification to help build 80% of the code and other deliverables. This 20% can vary according to the type of project: real-time systems, telecommunications, web applications, business applications, etc. What is considered essential may vary according to the kind of project, but in all cases the unused 80% obscures and complicates the essential.

To address this complaint, UML should be described differently for different user groups. There are ordinary users such as analysts, designers, website builders, database designers, developers, operators, architects, and testers, each bringing a different -- but valid -- perspective that uses different but overlapping subsets of UML. A particular class of users comprises the designers of UML itself and UML tool builders. It goes without saying that if the language is complex, these designers will have a hard time creating a language that is complete, consistent, extensible, and able to integrate with other languages, and the number of specification defects will become high.

Figure 1 depicts the main components of UML 2 and the dependencies between them. Although there is some layering, the overall structure contains a lot of cyclic dependencies, which makes it difficult to define useful subsets of the language. The UML specification does define formal "compliance points" which supposedly describe legal subsets of UML, but UML tool vendors have taken little or no notice of these, because they do not correspond to important use cases for UML users.

Figure 1: Components and Dependencies of UML 2.

A key point with the current UML is that there is no way in a compliant implementation to use the simple version of a concept without having the complicated version; for example, take Class. Most users think of a Class as a simple thing that has attributes, operations, inheritance etc. But a UML 2 class also has Ports, Parts, Connectors, and Receptions -- concepts only useful in specialized domains. There is no way to have just the simple one, so all users are burdened with the understanding required by advanced users. This can be -- and is -- mitigated to some extent by good tools. However, we believe that the simple options should be inherent in the language definition itself. Furthermore, the UML Class differs in detail from the concept of Class found in any particular programming language, which introduces additional conceptual barriers between UML and those of its users who are software developers. Again, flexibility of these definitions should be inherent in the language, so that it can be fine-tuned to match to modern programming technologies.

In summary, there are two major challenges to be addressed: complexity of the UML specification itself, and the need to describe UML in coherent subsets that address the actual needs of users in particular domains.

To address the first challenge, as a direct response to the feedback from the RFI, the OMG has embarked on a program of simplification for the UML specification. By the middle of 2011, a much simplified version of the UML specification should be available in which cyclic dependencies and redundancy have been greatly reduced. This specification will be compatible with existing tools and models, but described in a way that makes it much more amenable to further simplification and integration.

Refactoring UML
Once the simplification of the UML specification is complete in 2011, we will be able to move onto the next phase, which will be to refactor UML so that it can more effectively address the changing needs of many different classes of users. This section proposes some techniques that we can apply for this. It will be very important to retain backwards compatibility with the existing UML while doing this: we must not introduce changes that invalidate existing investments in tools, models or training.

We suggest it is possible to create a very small kernel of no more than 20 elements such as objects, links, types and actions, so that almost everyone can learn it in a few hours. In these elements, we will only add things that are necessary to understand the kernel, so that it in a way becomes complete. The kernel by itself is not particularly useful to any developer as it is, although it might suffice for abstract conceptual modeling. It is intended to serve as a basis to describe useful elements.

On top of the kernel we now add more useful concepts. The most essential UML use cases can be defined as extensions to the kernel. An example of an essential use case of UML would be: "Developing from requirements to test".

Figure 2: Suggested simplification of UML through separation of concerns.

The key idea here is that the kernel should be kept small and only includes generic elements and attributes needed by most use cases of UML. Specific elements or attributes to existing elements in the kernel which are needed to provide support for the use case "Developing from requirements to test" are added along with that use case. Thus they don't belong to the kernel. Everything new is added with the new use case, since it supports the use case. This is the whole point. This is what is called an "aspect-oriented structure", where the kernel can be kept clean and simple without knowledge of how it will be extended. The new additions to the kernel will be added with the new elements coming with the use cases that need them.

Returning to the use case example of "Developing from requirements to test".... There are many specializations of this use case; for example, "Developing a web application from requirements to test", and variants such as complex system, distributed system, which all wouldn't be essentials, but extensions to the essential use cases.

Figure 3: Adding a non-essential use case.
Since the use case "Developing from requirements to test" in itself is a large use case, we would need to find its constituent smaller use cases: Use case modeling, Designing, Implementing, Testing, Deploying. They are all different aspects or separate concerns of UML (see " Aspect-Oriented Software Development With Use Cases). Note that there is a danger in breaking down the complete use case into constituent use cases, which is that it might create silos and increase the risk of getting waste, contradicting principles of lean development. We mitigate this by using the Framework design principle where "each component should only do what only that component can do". This forces clean minimal factoring.

Figure 4: Constituent use cases of the larger use case "Developing from requirements to test".
Technically, we need some enhancements to the mechanisms used to extend UML. Today there is a mechanism called Profiles which provides some of the required capability but is not well integrated with the rest of the UML architecture. A simple new mechanism for extending UML -- multiple dynamic classification of model elements -- is currently under development at the OMG, and is scheduled to be available as an OMG standard in 2011. This enables, for example, the specification of Ports to be completely separated from the specification of Classes, so that Ports can be added to Classes only for those advanced use cases where they are required.

Structuring UML like this will help eliminate today’s dilemma of choosing between UML and one or more domain-specific languages (DSLs). When UML is structured as a simple kernel plus extensions, new domains can be addressed by crafting further extensions that can be seamlessly integrated with the existing structures. Another mechanism currently under development at the OMG -- Diagram Definition -- will enable new standard diagram types to be specified and integrated with existing ones. Diagram Definition is also scheduled to be available as an OMG standard in 2011, and will be applied to UML and to other modeling languages including BPMN (Business Process Model and Notation).

To help users get started we should define a basic subset of UML, here called "Essential UML", which can be learnt quickly in a few days. This would include the simple aspects of most of the familiar UML diagrams. The rest of the UML can be added as a set of seamlessly interwoven, deeply integrated yet completely independent extensions without altering what already has been described, and taught. This is smart!

During the last 10 years UML has not adapted quickly enough to developments in the software world. Ten years ago, for example we didn’t have so many frameworks. Today we are inundated with frameworks. The work of programming has increasingly moved to become a job of connecting already developed components or to use existing frameworks. The amazing production of apps for mobile phones is a perfect example. Today, we have not found a place for UML in this context. That does not mean that such a place does not exist, just that we have not yet adapted UML to this context or made UML appetizing to use in these contexts.

As we move forward with improving the UML, however, the first step is to simplify the existing UML, so we get it to become what UML should have been. We need to shrink UML first to lay the foundation for radical expansion of UML into many different new and exciting domains. As the basis for this work is being laid, we can begin to enrich UML with the possible new constructs we need today and tomorrow.

As a consequence of these developments, users can carry on investing in UML with confidence that the value of their investment will grow as UML moves into new domains, and becomes easier to apply and to integrate with other technologies. Sphere: Related Content

The Boost.Threads Library

By Bill Kempf, May 01, 2002

Standard C++ threads are imminent and will derive from the Boost.Threads library, explored here by the library's author.

Important Update
For an update of the Boost.Threads library, see the article What's New in Boost Threads? by Anthony Williams, maintainer of the Boost.Threads Library. This update appears in the November 2008 issue of Dr. Dobb's Journal.
--------------------------------------------------------------------------------
Just a few years ago it was uncommon for a program to be written with multiple threads of execution. Today Internet server applications run multiple threads of execution to efficiently handle multiple client connections. To maximize throughput, transaction servers execute services on separate threads. GUI applications perform lengthy operations in a separate thread to keep the user interface responsive. The list goes on.
The C++ Standard doesn’t mention threads, leaving programmers to wonder whether it’s even possible to write multithreaded C++ programs. Though it is not possible to write standards-compliant multithreaded programs, programmers none the less write multithreaded programs in C++ using the libraries provided by their OS that expose the system’s support for threads. However, there are at least two major problems with doing this: these libraries are almost universally C libraries and require careful use in C++, and each OS provides its own set of libraries for handling multithreaded support. Therefore, the resulting code is not only non-standard, but also non-portable [1]. Boost.Threads is a library designed to address both problems.
Boost [2] is an organization started by members of the C++ Standards Committee Library Working Group to develop new source libraries for C++. Its current membership includes approximately 2,000 members. Many libraries can be found in the Boost source distribution [3]. To make these libraries thread-safe, Boost.Threads was created.
Many C++ experts provided input to the design of Boost.Threads. The interface was designed from the ground up and is not just a simple wrapper around any C threading API. Many features of C++ (such as the existence of constructors/destructors, function objects, and templates) were fully utilized to make the interface more flexible. The current implementation works for POSIX, Win32, and Macintosh Carbon platforms.

Thread Creation
The boost::thread class represents a thread of execution in the same way the std::fstream class represents a file. The default constructor creates an instance representing the current thread of execution. An overloaded constructor takes a function object called with no arguments and returning nothing. This constructor starts a new thread of execution, which in turn calls the function object.
At first it appears that this design is less useful than the typical C approach to creating a thread where a void pointer can be passed to the routine called by the new thread, which allows data to be passed. However, because Boost.Threads uses a function object instead of just a function pointer, it is possible for the function object to carry data needed by the thread. This approach is actually more flexible and is type safe. When combined with functional libraries, such as Boost.Bind, this design actually allows you to easily pass any amount of data to the newly created thread.
Currently, not a lot can be done with a thread object created in Boost.Threads. In fact only two operations can be performed. Thread objects can easily be compared for equality or inequality using the == and != operators to verify if they refer to the same thread of execution, and you can wait for a thread to complete by calling boost::thread::join. Other threading libraries allow you to perform other operations with a thread (for example, set its priority or even cancel it). However, because these operations don’t easily map into portable interfaces, research is being done to determine how they can be added to Boost.Threads.
Listing 1 illustrates a very simple use of the boost::thread class. A new thread is created that simply writes “Hello World” out to std::cout, while the main thread waits for it to complete.

Mutexes
Anyone who has written a multithreaded program understands how critical it is for multiple threads not to access shared resources at the same time. If one thread tries to change the value of shared data at the same time as another thread tries to read the value, the result is undefined behavior. To prevent this from happening, make use of some special primitive types and operations. The most fundamental of these types is known as a mutex (the abbreviation for “mutual exclusion”). A mutex allows only a single thread access to a shared resource at one time. When a thread needs to access the shared resource, it must first “lock” the mutex. If any other thread has already locked the mutex, this operation waits for the other thread to unlock the mutex first, thus ensuring that only a single thread has access to the shared resource at a time.
The mutex concept has several variations. Two large categories of mutexes that Boost.Threads supports include the simple mutex and the recursive mutex. A simple mutex can only be locked once. If the same thread tries to lock a mutex twice, it deadlocks, which indicates that the thread will wait forever. With a recursive mutex, a single thread may lock a mutex several times and must unlock the mutex the same number of times to allow another thread to lock the mutex.
Within these two broad categories of mutexes, there are other variations on how a thread can lock the mutex. A thread may attempt to lock a mutex in three ways:
1. Try and lock the mutex by waiting until no other thread has the mutex locked.
2. Try and lock the mutex by returning immediately if any other thread has the mutex locked.
3. Try and lock the mutex by waiting until no other thread has the mutex locked or until a specified amount of time has elapsed.
It appears that the best possible mutex type is a recursive type that allows all 3 forms of locking. However, overhead is involved with each variation,so Boost.Threads allows you to pick the most efficient mutex type for your specific needs. This leaves Boost.Threads with six mutex types, listed in order of preference based on efficiency: boost::mutex, boost::try_mutex, boost::timed_mutex, boost::recursive_mutex, boost::recursive_try_mutex, and boost::recursive_timed_mutex.
Deadlock may occur if every time a mutex is locked it is not subsequently unlocked. This is the most common possible error, so Boost.Threads is designed to make this impossible (or at least very difficult). No direct access to operations for locking and unlocking any of the mutex types is available. Instead, mutex classes define nested typedefs for types that implement the RAII (Resource Acquisition in Initialization) idiom for locking and unlocking a mutex. This is known as the Scoped Lock [4] pattern. To construct one of these types, pass in a reference to a mutex. The constructor locks the mutex and the destructor unlocks it. C++ language rules ensure the destructor will always be called, so even when an exception is thrown, the mutex will always be unlocked properly.
This pattern helps to ensure proper usage of a mutex. However, be aware that although the Scoped Lock pattern ensures that the mutex is unlocked, it does not ensure that any shared resources remain in a valid state if an exception is thrown; so just as with programming for a single thread of execution, ensure that exceptions don’t leave the program in an inconsistent state. Also, the locking objects must not be passed to another thread, as they maintain state that’s not protected from such usage.
Listing 2 illustrates a very simple use of the boost::mutex class. Two new threads are created, which loop 10 times, writing out an id and the current loop count to std::cout, while the main thread waits for both to complete. The std::cout object is a shared resource, so each thread uses a global mutex to ensure that only one thread at a time attempts to write to it.
Many users will note that passing data to the thread in Listing 2 required writing a function object by hand. Although the code is trivial, it can be tedious writing this code every time. There is an easier solution, however. Functional libraries allow you to create new function objects by binding another function object with data that will be passed to it when called. Listing 3 shows how the Boost.Bind library can be used to simplify the code from Listing 2 by removing the need for a hand-coded function object.

Condition Variables
Sometimes it’s not enough to lock a shared resource and use it. Sometimes the shared resource needs to be in some specific state before it can be used. For example, a thread may try and pull data off of a stack, waiting for data to arrive if none is present. A mutex is not enough to allow for this type of synchronization. Another synchronization type, known as a condition variable, can be used in this case.
A condition variable is always used in conjunction with a mutex and the shared resource(s). A thread first locks the mutex and then verifies that the shared resource is in a state that can be safely used in the manner needed. If it’s not in the state needed, the thread waits on the condition variable. This operation causes the mutex to be unlocked during the wait so that another thread can actually change the state of the shared resource. It also ensures that the mutex is locked when the thread returns from the wait operation. When another thread changes the state of the shared resource, it needs to notify the threads that may be waiting on the condition variable, enabling them to return from the wait operation.
Listing 4 illustrates a very simple use of the boost::condition class. A class is defined implementing a bounded buffer, a container with a fixed size allowing FIFO input and output. This buffer is made thread-safe internally through the use of a boost::mutex. The put and get operations use a condition variable to ensure that a thread waits for the buffer to be in the state needed to complete the operation. Two threads are created, one that puts 100 integers into this buffer and the other pulling the integers back out. The bounded buffer can only hold 10 integers at one time, so the two threads wait for the other thread periodically. To verify that it is happening, the put and get operations output diagnostic strings to std::cout. Finally, the main thread waits for both threads to complete.

Thread Local Storage
Many functions are not implemented to be reentrant. This means that it is unsafe to call the function while another thread is calling the same function. A non-reentrant function holds static data over successive calls or returns a pointer to static data. For example, std::strtok is not reentrant because it uses static data to hold the string to be broken into tokens.
A non-reentrant function can be made into a reentrant function using two approaches. One approach is to change the interface so that the function takes a pointer or reference to a data type that can be used in place of the static data previously used. For example, POSIX defines strtok_r, a reentrant variant of std::strtok, which takes an extra char** parameter that’s used instead of static data. This solution is simple and gives the best possible performance; however, it means changing the public interface, which potentially means changing a lot of code. The other approach leaves the public interface as is and replaces the static data with thread local storage (sometimes referred to as thread-specific storage).
Thread local storage is data that’s associated with a specific thread (the current thread). Multithreading libraries give access to thread local storage through an interface that allows access to the current thread’s instance of the data. Every thread gets its own instance of this data, so there’s never an issue with concurrent access. However, access to thread local storage is slower than access to static or local data; therefore it’s not always the best solution. However, it’s the only solution available when it’s essential not to change the public interface.
Boost.Threads provides access to thread local storage through the smart pointer boost::thread_specific_ptr. The first time every thread tries to access an instance of this smart pointer, it has a NULL value, so code should be written to check for this and initialize the pointer on first use. The Boost.Threads library ensures that the data stored in thread local storage is cleaned up when the thread exits.
Listing 5 illustrates a very simple use of the boost::thread_specific_ptr class. Two new threads are created to initialize the thread local storage and then loop 10 times incrementing the integer contained in the smart pointer and writing the result to std::cout (which is synchronized with a mutex because it is a shared resource). The main thread then waits for these two threads to complete. The output of this example clearly shows that each thread is operating on its own instance of data, even though both are using the same boost::thread_specific_ptr.

Once Routines
There’s one issue left to deal with: how to make initialization routines (such as constructors) thread-safe. For example, when a “global” instance of an object is created as a singleton for an application, knowing that there’s an issue with the order of instantiation, a function is used that returns a static instance, ensuring the static instance is created the first time the method is called. The problem here is that if multiple threads call this function at the same time, the constructor for the static instance may be called multiple times as well, with disastrous results.
The solution to this problem is what’s known as a “once routine.” A once routine is called only once by an application. If multiple threads try to call the routine at the same time, only one actually is able to do so while all others wait until that thread has finished executing the routine. To ensure that it is executed only once, the routine is called indirectly by another function that’s passed a pointer to the routine and a reference to a special flag type used to check if the routine has been called yet. This flag is initialized using static initialization, which ensures that it is initialized at compile time and not run time. Therefore, it is not subject to multithreaded initialization problems. Boost.Threads provides calling once routines through boost::call_once and also defines the flag type boost::once_flag and a special macro used to statically initialize the flag named BOOST_ONCE_INIT.
Listing 6 illustrates a very simple use of boost::call_once. A global integer is statically initialized to zero and an instance of boost::once_flag is statically initialized using BOOST_ONCE_INIT. Then main starts two threads, both trying to “initialize” the global integer by calling boost::call_once with a pointer to a function that increments the integer. Next main waits for these two threads to complete and writes out the final value of the integer to std::cout. The output illustrates that the routine truly was only called once because the value of the integer is only one.

The Future of Boost.Threads
There are several additional features planned for Boost.Threads. There will be a boost::read_write_mutex, which will allow multiple threads to read from the shared resource at the same time, but will ensure exclusive access to any threads writing to the shared resource. There will also be a boost::thread_barrier, which will make a set of threads wait until all threads have “entered” the barrier. A boost::thread_pool is also planned to allow for short routines to be executed asynchronously without the need to create or destroy a thread each time.
Boost.Threads has been presented to the C++ Standards Committee’s Library Working Group for possible inclusion in the Standard’s upcoming Library Technical Report, as a prelude to inclusion in the next version of the Standard. The committee may consider other threading libraries; however, they viewed the initial presentation of Boost.Threads favorably, and they are very interested in adding some support for multithreaded programming to the Standard. So, the future is looking good for multithreaded programming in C++.

Listing 1: The boost::thread class
#include ^boost/thread/thread.hpp^
#include ^iostream^

void hello()
{
std::cout <<
"Hello world, I'm a thread!"
<< std::endl;
}

int main(int argc, char* argv[])
{
boost::thread thrd(&hello);
thrd.join();
return 0;
}
— End of Listing —


Listing 2: The boost::mutex class
#include ^boost/thread/thread.hpp^
#include ^boost/thread/mutex.hpp^
#include ^iostream^

boost::mutex io_mutex;

struct count
{
count(int id) : id(id) { }

void operator()()
{
for (int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << id << ": "
<< i << std::endl;
}
}

int id;
};

int main(int argc, char* argv[])
{
boost::thread thrd1(count(1));
boost::thread thrd2(count(2));
thrd1.join();
thrd2.join();
return 0;
}
— End of Listing —


Listing 2: DEAD LINK

Listing 4: The boost::condition class
#include ^boost/thread/thread.hpp^
#include ^boost/thread/mutex.hpp^
#include ^boost/thread/condition.hpp^
#include ^iostream^

const int BUF_SIZE = 10;
const int ITERS = 100;

boost::mutex io_mutex;

class buffer
{
public:
typedef boost::mutex::scoped_lock
scoped_lock;

buffer()
: p(0), c(0), full(0)
{
}

void put(int m)
{
scoped_lock lock(mutex);
if (full == BUF_SIZE)
{
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout <<
"Buffer is full. Waiting..."
<< std::endl;
}
while (full == BUF_SIZE)
cond.wait(lock);
}
buf[p] = m;
p = (p+1) % BUF_SIZE;
++full;
cond.notify_one();
}

int get()
{
scoped_lock lk(mutex);
if (full == 0)
{
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout <<
"Buffer is empty. Waiting..."
<< std::endl;
}
while (full == 0)
cond.wait(lk);
}
int i = buf[c];
c = (c+1) % BUF_SIZE;
--full;
cond.notify_one();
return i;
}

private:
boost::mutex mutex;
boost::condition cond;
unsigned int p, c, full;
int buf[BUF_SIZE];
};

buffer buf;

void writer()
{
for (int n = 0; n < ITERS; ++n)
{
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << "sending: "
<< n << std::endl;
}
buf.put(n);
}
}

void reader()
{
for (int x = 0; x < ITERS; ++x)
{
int n = buf.get();
{
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << "received: "
<< n << std::endl;
}
}
}

int main(int argc, char* argv[])
{
boost::thread thrd1(&reader);
boost::thread thrd2(&writer);
thrd1.join();
thrd2.join();
return 0;
}
— End of Listing —


Listing 5: The boost::thread_specific_ptr class
#include ^boost/thread/thread.hpp^
#include ^boost/thread/mutex.hpp^
#include ^boost/thread/tss.hpp^
#include ^iostream^

boost::mutex io_mutex;
boost::thread_specific_ptr ptr;

struct count
{
count(int id) : id(id) { }

void operator()()
{
if (ptr.get() == 0)
ptr.reset(new int(0));

for (int i = 0; i < 10; ++i)
{
(*ptr)++;
boost::mutex::scoped_lock
lock(io_mutex);
std::cout << id << ": "
<< *ptr << std::endl;
}
}

int id;
};

int main(int argc, char* argv[])
{
boost::thread thrd1(count(1));
boost::thread thrd2(count(2));
thrd1.join();
thrd2.join();
return 0;
}
— End of Listing —


Listing 6: A very simple use of boost::call_once
#include ^boost/thread/thread.hpp^
#include ^boost/thread/once.hpp^
#include ^iostream^

int i = 0;
boost::once_flag flag =
BOOST_ONCE_INIT;

void init()
{
++i;
}

void thread()
{
boost::call_once(&init, flag);
}

int main(int argc, char* argv[])
{
boost::thread thrd1(&thread);
boost::thread thrd2(&thread);
thrd1.join();
thrd2.join();
std::cout << i << std::endl;
return 0;
}
— End of Listing —


NOTES
[1] The POSIX standard defines multithreaded support in what’s commonly known as the pthread library. This provides multithreaded support for a wide range of operating systems, including Win32 through the pthreads-win32 port. However, this is a C library that fails to address some C++ concepts and is not available on all platforms.
[2] Visit the Boost website at http://www.boost.org.
[3] See Bjorn Karlsson’s article, “Smart Pointers in Boost,” in C/C++ Users Journal, April 2002.
[4] Douglas Schmidt, Michael Stal, Hans Rohnert, and Frank Buschmann. Pattern-Oriented Software Architecture Volume 2 — Patterns for Concurrent and Networked Objects (Wiley, 2000).

William E. Kempf received his BS in CompSci/Math from Doane College. He’s been in the industry for 10 years and is currently a senior application developer for First Data Resources, Inc. He is the author of the Boost.Threads library, and an active Boost member. He can be contacted at wekempf@cox.net. Sphere: Related Content