Chapter 2 Managing thread

Basic Thread Manager 2.1

1. Do not wait for the completion of the start-up mode thread

#include<iostream>
#include<thread>
#include<cstring>

using namespace std;


void print(){
    cout << "hello world" << endl;
}


int main(){

    thread t(print);
    t.detach();
    
    return 0;
}

//------运行结果------------
/*
PS E:\Desktop> g++ -std=c++11 .\1.cpp
PS E:\Desktop> a
PS E:\Desktop>
*/

  UNIX-thread start in the process similar to a daemon thread, threads are separated (refer to the concept of UNIX daemon thread, and is commonly referred to as separate threads daemon thread).

2. Complete the way of waiting threads

#include<iostream>
#include<thread>
#include<cstring>

using namespace std;


void print(){
    cout << "hello world" << endl;
}


int main(){

    thread t(print);
    if(t.joinable())
        t.join();
    
    return 0;
}



//----------------运行结果-------------------
/*

PS E:\Desktop> g++ -std=c++11 .\1.cpp
PS E:\Desktop> a
hello world

*/

2.2 pass parameters to the thread function

#include<iostream>
#include<thread>
#include<cstring>

using namespace std;


void print(string s){
    cout << s << endl;
}


int main(){
    thread t(print, "hello world");
    if(t.joinable()) 
        t.join();
    
    return 0;
}

  When carrying out the transmission parameters can be transmitted in the thread of the constructed object.

2.3 Transfer Object Ownership

thread object as the object may be used as an ordinary form t1 = std :: mvoe (t), is the transfer of ownership.

2.4 Select the number of threads at runtime

Due to thread switching is to consume resources So when using a multi-threaded concurrent programming to consider the number of hardware threads, if the processor supports only one thread, our code open multiple threads, so making the cut threads, also will declare it wasted a lot of time, so we can get the number of threads according to thread :: hardware_concurrency ().

#include<iostream>
#include<thread>
#include<cstring>

using namespace std;


int main(){
    cout << thread::hardware_concurrency() << endl;
    
    return 0;
}
//------------运行结果------
/*
PS E:\Desktop> g++ -std=c++11 .\1.cpp
PS E:\Desktop> a
4
*/

  My computer can be found to support four threads, so in turn the number of multi-threaded, try to choose about four.

 

Guess you like

Origin www.cnblogs.com/hebust-fengyu/p/12077200.html