What Is Multi-Threading?
Of course, this problem has a much more elegant solution: avoid using the global data in the first place. In Listing 4, the loop counter is local to the function and there is no conflict; each call to the function has its own version of i, and so each thread which calls that function will have its own version of i.
However, two (or more) different threads can be inside the loop at the same time and so the output can be interlaced, as we originally expected. For example:
0 1 0 1 2 2 3 3
If it is not appropriate for your application to have more than one thread within a certain piece of code at the same time (this piece of code is commonly referred to as a critical section), you may still wish to use mutexes, even though you do not have shared data.
Remember, though, critical sections can negate some of the advantages of multi-threading by forcing threads to wait for others. It is a good idea to keep any necessary critical sections as short as possible.
What the programmer may need to be aware of is whether the other libraries being used are thread-safe or not. Otherwise, problems such as those described above may (or, more likely, will) occur. A good example is with every C and C++ programmer's friend, errno. When a system call fails for some reason, it is common for the function called to return a generic failure value (such as NULL or -1) and an indication of why it failed in errno--which is, of course, a global variable. Just think of the confusion if one thread calls putenv(), which fails and sets errno to ENOMEM. Then there is a context switch and another thread calls open() and fails, setting errno to ELOOP. Then there is another context switch; the return value from putenv() is checked, the failure is spotted, and confusion breaks out because it looks like putenv() failed with ELOOP, which is not possible.
Or consider the standard function strtok(). This breaks a string into tokens and works in two ways. On the first call, you pass in a string which is to be tokenised. It stores this string in a static area. On subsequent calls you pass in a NULL string and strtok() works its way through the already stored string. If two threads call strtok() concurrently, the first one will have its stored string overwritten by the string that the second tells strtok() to store.
Fortunately, thread-safe versions of errno and thread-safe versions of standard functions within libraries are now available. Take a look at /usr/include/errno.h, for example. If you have a recent set of include files you may find the following bit of code:
#if defined(_POSIX_THREAD_SAFE_FUNCTIONS) || \ defined(_REENTRANT) extern int* __errno_location __P((void)); #define errno (*__errno_location ()) #else extern int errno; #endif
errno is redefined to be an int returned by a function, rather than the usual global variable, when either \_POSIX\_THREAD\_SAFE\_FUNCTIONS or \_REENTRANT has been defined.
When compiling code for multi-threaded programs, always use:
in your code (or use the compiler option -D\_REENTRANT to make use of this thread-safe macro for errno).
Similarly, recent versions of libc contain thread-safe versions of standard unsafe functions. So there is now the usual unsafe strtok(), but also a thread-safe function strtok\_r()--see your man pages for the details.
All this, and we still haven't created a thread! Okay, let's put that right. Listing 5 is a very trivial, and complete, example of a multi-threaded program.
When I compile (with cc helloworld.c -o helloworld -lpthread) and run this program, I get the output: Hello world world Hello Hello world world Hello Hello world world Hello Hello world world Hello Hello world world Hello
Let's take a look at this program. There is a mutex variable printfLock; this may not be strictly necessary, but it is included just in case we are not using a thread-safe version of libc—just to be safe, mutex locking is put around the call to printf().
There are two new function calls in main(): pthread\_create() and pthread\_join(). The first of these, not surprisingly, creates a new thread. The first parameter points to a variable of type pthread\_t; this can be used to identify the newly created thread, not unlike the file-handle returned from the fopen() call. The second parameter allows you to set various attributes for the new thread. If the value is NULL, default attributes are used, and this is fine for now. The third parameter is the function which the thread is to execute; this is always a function which takes a void* as a parameter and has a void* return value. The fourth parameter is the argument which is to be passed as a parameter to the thread function defined in parameter 3.
As soon as pthread\_create() has successfully created a new thread, the function which is passed as the third parameter will be running.
In this example, the thread function takes a string as an argument and prints that string ten times before exiting. As you can see from the output, both threads execute at the same time and their output is interleaved.
The pthread\_join() function waits for the specified thread (identified using the pthread\_t variable returned in parameter one of the thread creation) to exit. A thread exits when the thread function returns, or when the thread makes an explicit call to the function pthread\_exit().
Fast/Flexible Linux OS Recovery
On Demand Now
In this live one-hour webinar, learn how to enhance your existing backup strategies for complete disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible full-system recovery solution for UNIX and Linux systems.
Join Linux Journal's Shawn Powers and David Huffman, President/CEO, Storix, Inc.
Free to Linux Journal readers.Register Now!
- Server Hardening
- May 2016 Issue of Linux Journal
- EnterpriseDB's EDB Postgres Advanced Server and EDB Postgres Enterprise Manager
- The Humble Hacker?
- BitTorrent Inc.'s Sync
- The Death of RoboVM
- The US Government and Open-Source Software
- New Container Image Standard Promises More Portable Apps
- Open-Source Project Secretly Funded by CIA
- ACI Worldwide's UP Retail Payments
In modern computer systems, privacy and security are mandatory. However, connections from the outside over public networks automatically imply risks. One easily available solution to avoid eavesdroppers’ attempts is SSH. But, its wide adoption during the past 21 years has made it a target for attackers, so hardening your system properly is a must.
Additionally, in highly regulated markets, you must comply with specific operational requirements, proving that you conform to standards and even that you have included new mandatory authentication methods, such as two-factor authentication. In this ebook, I discuss SSH and how to configure and manage it to guarantee that your network is safe, your data is secure and that you comply with relevant regulations.Get the Guide