C++0x high concurrency [how to use concurrency]

what is concurrency

Concurrency refers to the simultaneous execution of multiple independent tasks. Concurrency can be seen everywhere in our life, such as: we can make a phone call while walking, sing and dance while we are walking, as small as an atom (each extra-nuclear electron revolves around the nucleus at high speed at the same time), as large as each celestial body in the universe according to its own trajectory Running these independently of each other at the same time can be considered concurrent.

Concurrency in the computer world

[Single-core CPU] The concurrency on a single-core system is not the concurrency of the real physical structure. It is the illusion that concurrency is achieved by switching multiple tasks on the core CPU to make people think that two applications or tasks are running at the same time, but in fact it is Task switching in a short time through time slicing.

[Multi-core CPU] Compared with the single-core system, the multi-core system achieves concurrency in the true physical sense, and different applications or tasks can be assigned to different CPUs to complete.

Ways to implement concurrency

[Multi-process] The operating system provides protection operations and communication mechanisms between processes, making it easier to write safe concurrent code than threads. And can run on the same machine or on different machines. The availability and feasibility of this concurrency is of great use by leveraging the network.

[Multi-threading] Compared with multi-process threads, it is lightweight and does not need to occupy additional overhead at startup like processes. And the global data in the thread is still global, which makes communication between threads easy, but it is up to the programmer to manage this sharing to avoid unnecessary conflicts and ambiguities.

C++0x thread library

///[Member functions]
//default constructor
thread() noexcept;
//Initialize the constructor
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
//copy constructor, thread object cannot be copied
thread(thread&) = delete;
thread(const thread&) = delete;
thread& operator=(const thread&) = delete;
//move constructor
thread(thread&& __t) noexcept
{ swap(__t); }
thread& operator=(thread&& __t) noexcept
{
  if (joinable())std::terminate();
  swap(__t);
  return *this;
}
//destructor
~thread()
{if (joinable())std::terminate();}
//get the number of CPU cores
static unsigned int hardware_concurrency();
//Get the native thread ID
thread::native_handle_type native_handle();
//Get the thread ID provided by c+0x
thread::id get_id() const noexcept
//exchange thread state
void swap(thread& __t) noexcept
{ std::swap(_M_id, __t._M_id); }
//whether the thread object is joinable.
bool joinable() const noexcept
{ return !(_M_id == id()); }
//The function returns when the thread execution has completed.
void join();
//Separate the thread and let the thread run by itself
void detach();
/************************************/
//[namespace] this_thread
//Returns the thread id of the calling thread
thread::id get_id() noexcept
//It is to let the current thread give up its own CPU time slice to other threads)
void yield() noexcept
//
void __sleep_for(chrono::seconds, chrono::nanoseconds);
//
template<typename _Rep, typename _Period>
void sleep_for(const chrono::duration<_Rep, _Period>& __rtime)
//
template<typename _Clock, typename _Duration>
void sleep_until(const chrono::time_point<_Clock, _Duration>& __atime)

concurrent world

#include <iostream>
#include <functional>
#include <thread>
#include <string>
using namespace std;

void hello_thread(const std::string& thread_name)
{
    cout<<"["<<this_thread::get_id()<<"]-->"
        <<thread_name<<"-->"
        <<"Hello World"<<endl;
}


int main(int argc, char *argv[])
{
    thread th1,th2(hello_thread,"th2"),th3(std::move(th2));
    th1.joinable()?th1.join(),1:0;
    th2.joinable()?th2.detach(),1:0;
    th3.joinable()?th3.join(),1:0;

    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324733291&siteId=291194637