Bit-Currency source Analysis (2)-Preparation knowledge-Boost

Source: Internet
Author: User
Tags mutex
0x00 Introduction

Boost is an open source, Cross-platform, powerful C + + library, and is in addition to the most commonly used libraries outside the STL, to achieve a lot of basic operations, can make development more simple and fast. Below we will introduce Bitcoin source of the main use of some of the classes, official documents see: HTTP://WWW.BOOST.ORG/DOC/LIBS/1_65_0/, each of these classes also contains a very powerful function, so it is not just a few chapters can be introduced, Here is a brief introduction to their basic usage, in order to understand the source code in bitcoin, and the article will also give some reference materials for more detailed understanding.

Hint: The following code in the Ubuntu 16.04 LTS Environment compiled and run through, the process of testing mainly encountered two problems (1) undefined reference to Boost::system::generic_category ( , and so on, such as an undefined reference error, the workaround is to g++ Example.cpp-lboost_system-lboost_thread, which is to add a link library after the compilation parameter, and then adding the corresponding library based on the error. (2) Template argument Deduction/substitution failed this error is due to the name of the function and the function name of the system conflict, such as your program defined a void count () {} function, the compilation process will appear this error , many of the online boost thread tutorials define the Count function as an example, and those examples run in at least the Ubuntu environment, so the function name is not as easy to name as possible, even if there is a similar error can try to modify the function name. 0x01 Signals2

This part of the introduction of the main reference: http://blog.csdn.net/zengraoli/article/details/9697841

SIGNALS2 is another library signals based on boost, which implements a thread-safe observer pattern. The observer pattern is defined as a one-to-many dependency between objects, and when an object changes, all objects that depend on it are notified and automatically updated. (http://blog.csdn.net/wuzhekai1985/article/details/6674984) and in the SIGNALS2 library, the observer pattern is called the signal/slot (signals and slots), The official document explains it as

The BOOST.SIGNALS2 library is a implementation of a managed signals and slots system. Signals represent callbacks with multiple targets, and are also, called or events in publishers. Signals are connected to some set of slots, which are callback receivers (also called event targets or subscribers), which are called when the signal is "emitted."

The BOOST.SIGNALS2 library is an improved signal/slot system implementation. A signal is also called a publisher or event in a similar system, representing multiple callback destinations. The signal is connected to multiple slots, the receiver of the callback (also known as the event target or subscriber), and all associated slots are invoked when the signal is launched.

Signals and slots are managed, in which signals and slots (or, more properly, objects that occur as part of the slots) can Track connections and are capable to automatically disconnecting signal/slot connections when either is destroyed. This enables the user to make Signal/slot connections without expending a great effort to manage the lifetimes of those Co Nnections with regard to the lifetimes of all objects involved.

The signal/slot is designed to track the connection status and automatically disconnect when either of the two sides is destroyed. This allows the user to easily use the signal/slot connection, without having to manage the lifecycle of all the objects involved in the connection relationship.

in layman's terms, the signal is a trigger, the slot is some column callback function, when the signal launch, that is, trigger is triggered, all the callback function will be called. The function of the signal/slot mechanism is to bring together the functions associated with these functions, and to call them sequentially in a certain moment.

Once you understand what it's going to accomplish, let's look at a simple example.

Example1.cpp
#include <iostream>
#include "boost/signals2.hpp"
using namespace std;

void Slot1 () {
  cout << "Solt1 call" << Endl;
}

void Slot2 () {
  cout << "Solt2 call" << Endl;
}

int main () {
  boost::signals2::signal<void () > sig;  Define Signal
  Sig.connect (&SLOT1);  Signal associated slot
  sig.connect (&slot2);
  Sig ();  Departure signal return
  0;
}

My operating environment is the Ubuntu 16.04 LTS, using the command sudo apt-get install Libboost-all-dev after installing boost, you can use g++ example1.cpp to compile the run directly.

The above is only a simple introduction to the use of SIGNALS2, involving only the bucket of SIGNALS2, more detailed use of the students also ask their own access to relevant information. 0x02 Bind

This part of the reference: http://blog.csdn.net/zengraoli/article/details/9666943

First, refer to the above blog's introduction to bind:

Bind is not a separate class or function, but a very large family, with a total of dozens of different forms depending on the number of parameters that are bound and the type of invocation object to bind, but their names are called bind, and the compiler automatically determines the correct form to use based on the specific binding code.

The first parameter that bind accepts must be a section called Object F, which includes function pointers, function references, member function pointers, and function objects, and bind accepts up to nine arguments, the number of which must be equal to the number of parameters in F, which are passed to f as a formal parameter.

When binding is complete, BIND returns a function object that internally holds a copy of F, has operator (), and the return value type is automatically deduced to the return value type F. At the time of the call, this function object will transfer the previously stored arguments to F to complete the call.

In simple terms, the function of bind is to bind certain parameters to a function, where arguments have a very important concept called placeholders, defined as _1 to _9, and here's a simple example.

Example2.cpp
#include "boost/bind.hpp"
#include <iostream>
#include <vector>
using namespace Std;

int f (int a, int b) {return
  a+b;
}

int g (int A, int b, int c) {return
  a+b+c;
}

struct p{
  int x, y;
  P (int a=9, int b=9): X (a), Y (b) {}

  void print () {
    cout << "x:" << x << "y:" << Endl;
  }
};

int main () {
  int x = 1, y = 2, z = 3;
  cout << Boost::bind (f, x, y) () << Endl; f (x, y)
  cout << boost::bind (g, _1, _2, _3) (x, Y, z) << Endl;//g (x, Y, z)
  cout << boost::b IND (g, X, _2, x) (z, y, x) << Endl; g (x, y, x), the placeholder represents the actual incoming number of parameters

  vector<p> V (a);
  For_each (V.begin (), V.end (), Boost::bind (&p::p rint, _1)); Print:p.x, P.Y, when a member function is referenced, the placeholder first always represents the object instance return
  0;
0x03 Thread

Threads are a technique that is often used in a variety of projects, and generally mentioned threads will involve multithreading, the most classic problem is synchronous access to shared resources, and almost all other languages like boost is also through the provision of mutex to solve, but the difference is that boost provides multiple mutex classes, Allows the project to handle shared resources more flexibly.

Example3.cpp #include "boost/thread.hpp" #include <iostream> using namespace std;

Boost::mutex Mutex;

void Wait (int sec) {boost::this_thread::sleep (boost::p osix_time::seconds (sec));
    void work () {for (int i=0;i<5;i++) {wait (1);
  cout << "ID:" << 1 << "" << I << Endl;
    } void Work1 (int id) {for (int i=0;i<5;i++) {wait (1);
  cout << "ID:" << ID << "" << I << Endl;
    } void Work2 (int id) {for (int i=0;i<5;i++) {mutex.lock ();
    cout << "ID:" << ID << "" << I << Endl;

    Mutex.unlock ();  /******** Other mutex boost::lock_guard<boost::mutex> lock (mutex);
    Lock_guard automatically calls lock () and unlock (), respectively, on internal constructs and destructors, so it automatically sets the current domain as a mutually exclusive access zone.  For more information please refer to: http://zh.highscore.de/cpp/boost/multithreading.html ********************/} int main () {Boost::thread Th1 (&work); 
  The simplest invocation, with no parameters boost::thread Th2 (Boost::bind (&AMP;WORK1, 2)); Boost::threadTh3 (Boost::bind (&AMP;WORK1, 3)); Bind is an important application of binding parameters. 
  Here two threads do not add any mutex, print out is disorderly order Boost::thread Th4 (Boost::bind (&AMP;WORK2, 4)); Boost::thread Th5 (Boost::bind (&AMP;WORK2, 5));  4, 5 line Chengga simple mutex, results in order to print th1.join ();
  Blocks the current process, waits for the calling thread to complete, prevents the main line enters upgradeable end Th2.join ();
  Th3.join ();
  Th4.join ();  
  Th5.join ();
return 0; }
0x04 Chrono

Chrono is a library for time processing in the Boost library, consisting primarily of three conceptual time periods (duration), Point-in-time (Time_point), and Clocks (clock).

//example4.cpp #include <iostream> #include "boost/chrono.hpp" using namespace std;
Durations represents a period of time between the TypeDef boost::chrono::hours hours;
typedef boost::chrono::minutes minutes;
typedef boost::chrono::seconds seconds;
typedef boost::chrono::milliseconds milliseconds;
typedef boost::chrono::microseconds microseconds;

typedef boost::chrono::nanoseconds nanoseconds;
Clock represents the current time, is in constant change to the TypeDef boost::chrono::system_clock System_clock;
typedef boost::chrono::steady_clock Steady_clock;

typedef boost::chrono::high_resolution_clock High_resolution_clock;

Time point represents a specific point-in-time typedef system_clock::time_point SYS_TP;
  int main () {hours H1 (1);
  Minutes M1 (1); Minutes m2 = h1 + m1; can only be converted into smaller units cout << m2 << endl; Minutes hours H2 = Boost::chrono::d uration_cast

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.