Platform-independent multi-thread library-C ++ boost Thread Programming Guide)

Source: Internet
Author: User

New article: Construction of platform-independent programs



0 Preface

The standard C ++ thread is coming soon. Cuj predicts that it will be derived from the boost thread library, and now Bill will lead us to explore the boost thread library.

 

Just a few years ago, it was executed with multiple threads.ProgramIt is still an unusual thing. However, today, Internet application service applications generally use multithreading to improve the efficiency of connecting to multiple customers. In order to achieve maximum throughput
The transaction server runs the service program on a separate thread. GUI applications run the time-consuming and complex processing separately in the form of threads, this ensures that the user interface can respond to user operations in a timely manner. This
There are many examples of multithreading.

 

However, the C ++ standard does not involve multithreading, which leads programmers to doubt whether multi-threaded C ++ programs can be written. Although it is impossible for programmers to write standard multi-threaded programs
The multi-threaded C ++ program is written using the multi-threaded library provided by the multi-threaded operating system. But there are at least two problems: Most of these libraries are completed in C language.
You must be very careful when using these libraries. In addition, each operating system has its own set of multi-threaded class libraries. ThereforeCodeThere are no standards to follow, and they are not applicable everywhere (non-
Portable ). The boost thread library is designed to solve all these problems.

Boost is a member of the class library working group of the C ++ Standards Committee and is committed to developing new class libraries for C ++. It has nearly 2000 members. Many libraries can be found in the boost source code release. To make these class libraries thread-safe, the boost thread library is created.

Many C ++ experts are devoted to the development of boost thread libraries. The design of all interfaces starts from 0 and is not a simple encapsulation of the C-thread API. Many C ++ features (such as constructor and
Destructor, function object (Function
Object) and template) are used to make the interface more flexible. The current version can work on POSIX, Win32, and Macintosh carbon platforms.

1. Create thread

Just as the STD: fstream class represents a file, the boost: Thread class represents an executable thread. The default constructor creates an entity that represents the current execution thread.
Example. An overloaded constructor uses a function object without any parameters as a parameter and has no return value. This constructor creates a new executable thread that calls the function object.

 

At first, we thought that the traditional method of creating a thread in C seems to be more useful than this design, because C will input a void * pointer during thread creation, and data can be imported through this method. However,
Because the boost thread library uses a function object instead of a function pointer, the function object itself can carry the data required by the thread. This method is more flexible and also type-safe (Type-
Safe. When used with function libraries such as boost. Bind, This method allows you to transmit any amount of data to the new thread.

 

Currently, the thread object created by the boost thread library is not very powerful. In fact, it can only perform two operations. Convenient use of thread objects = and! = Compare to determine whether they represent
The same thread; you can also call boost: thread: join to wait for the thread to finish running. Other thread libraries allow you to perform other operations on the thread (such as setting the priority
To cancel the thread ). However, since it is not easy to add these operations to a commonly used (portable) interface, we are still discussing how to add these operation groups to the boost thread library.

 

Listing1 demonstrates a simple usage of the boost: Thread class. The new thread simply prints "Hello, world" on STD: out, and the main function ends after it is executed.

Example 1:

 
# Include <boost/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;
}

2 mutex

Anyone who has written a multi-threaded program knows the importance of preventing different threads from simultaneously accessing the shared area. If
The thread needs to change a data in the shared area while the other thread is reading the data, the result will be undefined. Some special primitive types and operations are required to avoid this situation. Its
The most basic is mutex (mutual
Exclusion ). A mutex allows only one thread to access the shared zone at a time. When a thread wants to access a shared zone, the first thing to do is to lock the mutex. If other
The thread has locked the mutex, so you must wait for the thread to unlock the mutex so that only one thread can access the shared zone at the same time.

 

The concept of mutex has many variants. The boost thread Library supports two types of mutex, including simple mutex and recursive
Mutex ). If the same thread has two locks on the mutex, a deadlock will occur. That is to say, all the threads waiting for unlocking will keep waiting. With recursive mutex, a single
The thread can lock the mutex multiple times. Of course, the same number of times must be unlocked to ensure that other threads can lock the mutex.

 

In these two major types of mutex, there are multiple variants about how to lock the thread. A thread can lock a mutex in three ways:

    1. Wait until no other threads lock the mutex.
    2. If another mutex has locked the mutex, return immediately.
    3. Wait until no other threads lock the mutex until it times out.

It seems that the optimal mutex type is recursive mutex, which can use all three locks. However, each variant has a price. Therefore, the boost thread library allows you to use the most efficient mutex type based on different needs. The boost thread Library provides the mutex type in step 6, which is sorted by efficiency as follows:

 

 
Boost: mutex,
Boost: try_mutex,
Boost: timed_mutex,
Boost: recursive_mutex,
Boost: recursive_try_mutex,
Boost: recursive_timed_mutex

If the mutex is unlocked, a deadlock occurs. This is a common error. The boost thread library is to make it impossible (at least difficult ). Lock and unlock mutex directly
It is impossible for users of the boost thread library. The mutex class locks and locks mutex by defining the types implemented in raiI. This is what everyone knows.
Scope
Lock mode. To construct these types, you must pass in a reference to the mutex. The constructor locks the mutex and the Destructor unlocks the mutex. C ++ ensures that the Destructor will be called.
If an exception is thrown, the mutex is always unlocked correctly.

This method ensures correct use of mutex. However, one thing you must note: although scope
The lock mode can ensure that the mutex is unlocked, but it does not guarantee that resources are still available after an exception is thrown. So just like executing a single-threaded program, you must ensure that exceptions do not cause program status exceptions.
. In addition, this locked object cannot be passed to another thread because the state they maintain is not prohibited.

 

List2 provides a simple example of using boost: mutex. In this example, two new threads are created, each of which has 10 loops, on STD: cout.
Print the thread ID and the number of current cycles, and the main function will not end until the execution of the two threads is complete. STD: cout is shared resources, so every thread uses a global mutex to protect
At the same time, only one thread can write data to it.

 

Many readers may have noticed that a function is required to manually write data to the thread in list2. Although this example is simple, it is annoying to write such code every time.
Don't worry. There is a simple solution. The function library allows you to create a new function by binding another function and passing in the required data.
List3 shows you how to use the boost. Bind library to simplify the code in list2, so you do not have to write these function objects manually.

Example 2:

# Include <boost/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;
}

Example 3: // This example is the same as Example 2. In addition to using boost. bind to simplify the creation of thread carrying data, avoid using function objects.

# Include <boost/thread. HPP>
# Include <boost/thread/mutex. HPP>
# Include <boost/Bind. HPP>
# Include <iostream>

Boost: mutex io_mutex;

Void count (int id)
{
For (INT I = 0; I <10; ++ I)
{
Boost: mutex: scoped_lock
Lock (io_mutex );
STD: cout <id <":" <
I <STD: Endl;
}
}

Int main (INT argc, char * argv [])
{
Boost: thread thrd1 (
Boost: BIND (& count, 1 ));
Boost: thread thrd2 (
Boost: BIND (& count, 2 ));
Thrd1.join ();
Thrd2.join ();
Return 0;
}

3. Condition Variables

Sometimes it is not enough to use shared resources by locking them. Sometimes shared resources can only be used in certain States. For example, if a thread needs to read data from the stack
If there is data, you must wait for the data to be pushed to the stack. In this case, it is not enough to use mutex for synchronization. Another synchronization method, conditional variables, can be used in this case.

 

The use of condition variables is always associated with mutex and shared resources. The thread first locks the mutex and then checks whether the shared resource is in a usable state. If not, the thread will wait.
Variable to be conditioned. To point to this operation, you must unlock the mutex while waiting so that other threads can access the shared resources and change its status. It also needs to ensure that the mutex is locked when the wait thread returns.
. When another thread changes the state of shared resources, it will notify the thread waiting for the conditional variable and return it to the waiting thread.

 

List4 is a simple example using boost: condition. There is a class that implements a bounded cache area and a fixed-size first-in-first-out container. Because mutex is used
Body boost: mutex, Which is thread-safe. Put and get use conditional variables to ensure the State required for the thread to wait for the operation to be completed. Two threads are created, one in
Put 100 integers in the buffer, and the other extracts them from the buffer. This bounded cache can only store 10 integers at a time, so the two threads must wait for another line periodically.
. To verify this, put and get output diagnostic statements in STD: cout. Finally, when the two threads are finished, the main function is executed.

 

# Include <boost/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. policy_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. policy_one ();
Return I;
}

PRIVATE:
Boost: 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;
}

 

4. Local thread storage

Most functions are not reentrant. This means that when a thread has already called a function, if you call the same function again, this is not safe. A non-reentrant function is called continuously.
Used to save static variables or return a pointer to static data.
For example, STD: strtok is not reentrant, because it uses static variables to save the string to be split into symbols.

 

There are two ways to convert reusable functions into reusable functions. The first method is to change the interface and replace the original static data with a pointer or reference. For example, POSIX defines
A reentrant variable in strok_r, STD: strtok. It uses an additional char ** parameter to replace static data. This method is simple and provides the best possible effect.
Result. However, the public interface must be changed, which means the Code must be changed. The other method does not need to change the public interface, but uses the local storage thread (Thread Local
Storage) to replace static data (sometimes also become special thread storage, thread-specific storage ).

 

The boost thread Library provides the smart pointer boost: thread_specific_ptr to access the local storage thread. Each thread uses this smart pointer for the first time.
For example, its initial value is null. Therefore, you must first check whether this parameter is null and assign a value to it. The boost thread library ensures that the data stored in the local storage thread is cleared after the thread ends.

 

List5 is a simple example of using boost: thread_specific_ptr. Two threads are created to initialize the local storage thread and there are 10
The value pointed to by the smart pointer is added each time and output to STD: cout (because STD: cout is a shared resource, so synchronize through mutex ). Main Line
Wait until the two threads end and then exit. From the output of this example, we can see that each thread processes its own data instance, even though they all use the same
Boost: thread_specific_ptr.

 

Example 5:

# Include <boost/thread. HPP>
# Include <boost/thread/mutex. HPP>
# Include <boost/thread/TSS. HPP>
# Include <iostream>

Boost: mutex io_mutex;
Boost: thread_specific_ptr <int> 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;
}

5. Only one running routine

Another problem persists: How to Make initialization (such as constructor) secure is also thread-safe. For example, if a reference program needs to generate a unique global object,
A function is called to return a static object. It must ensure that this static object is generated when it is called for the first time. The problem here is that if multiple threads call this function at the same time, the static
The constructor of the image will be called multiple times. This error is generated.

 

The solution to this problem is the "one-time implementation" (once
Routine ). "One-time implementation" can be executed only once in an application. If multiple threads want to execute this operation at the same time, only one is actually executed, and other threads must wait until this operation ends.
To ensure that it is executed only once, this routine is indirectly called by another function, and this function is passed to it as a pointer and a special mark indicating whether the routine has been called
Log. This flag is initialized in static mode, which ensures that it is initialized during compilation rather than runtime. Therefore, there is no problem of initializing multiple threads at the same time. Boost thread Library
Boost: call_once is provided to support "one-time implementation", and a boost: once_flag and a macro that initializes this flag are defined.
Boost_once_init.

 

List6 is an example using boost: call_once. A static global integer with an initial value of 0 and
Static boost: once_flag instance initialized by boost_once_init. The main function creates two threads, both of which want to pass in a function call.
Boost: call_once to initialize the global integer. This function adds 1 to it. The main function waits for two threads to end and outputs the final result
STD: cout. From the final result, we can see that this operation was actually executed only once, because its value is 1.

 

 
#include 
           
           
# include
# include
int I = 0;
boost: once_flag flag =
boost_once_init;
void Init ()
{< br> ++ I;
}< br>
void thread ()
{< br> boost: call_once (& init, flag);
}< br>
int main (INT argc, char * argv [])
{< br> boost: thread thrd1 (& THR EAD);
boost: thread thrd2 (& Thread);
thrd1.join ();
thrd2.join ();
STD :: cout return 0;
}

6. The future of the boost thread library

the boost thread library is planning to add some new features. This includes boost: read_write_mutex, which allows multiple threads to read data from the shared zone at the same time, but only one thread can write data to the shared zone at a time. Boost :: thread_barrier, which puts a group of threads in the waiting state, knowing that all the threads have entered the barrier
zone; Boost: thread_pool, it allows execution of some small routine without having to create or destroy each thread.

the boost thread library has been submitted to the C ++ Standards Committee as an appendix to the technical report of the standard class library, its appearance also sounded the first horn for the next C ++ standard. The Committee members spoke highly of the first draft of the
boost thread library. Of course, they will consider other multi-threaded libraries. They are very interested in adding multithreading support to the C ++ standard. From this point, we can also see that the future of multithreading in C ++ is bright.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.