C ++ 11 threads Precautions

1 . Copy constructor

thread (const thread &) = delete ;
copy constructor is disabled, std :: thread object is not copy constructor

2 . Move Constructor

thread (thread && x) noexcept
call succeeds original x is no longer a std :: thread objects

void threadFun(int& a)
{
    cout << "this is thread fun !" << endl;
}

int value = 2;
thread t1(threadFun, std::ref(value));
thread t2(std::move(t1));
t2.join();

3。get_id()

Get Thread ID, return type std :: thread :: id objects.

thread t1(threadFun);
thread::id threadId = t1.get_id();
cout << "线程ID:" << threadId << endl;

//threadId转换成整形值,所需头文件<sstream>
ostringstream   oss;
oss << t1.get_id();
string strId = oss.str();
unsigned long long tid = stoull(strId);
cout << "线程ID:" << tid << endl;

4. Create a thread, a reference parameter passing std :: ref ()

void threadFun1(int& v)
{
    cout << "this is thread fun1 !" << endl;
    cout << v << endl;
}

int main()
{
    int value = 6;
    thread t1(threadFun1, std::ref(value));
    t1.join();

    getchar();
    return 1;
}

5. Create a thread, function object parameter format

 struct fun_obj

{

void operator() () { do_something(); };

}

std :: thread td (fun_obj ()); // function declaration

the Thread :: td std ( (fun_obj ()) ); // create a thread

std :: thread td {fun_o bj ()}; // create a thread

fun_obj  obj;

std :: thread td (obj); // create a thread

6. Thread Parameters: function objects, reference character string (literal / char * / string problems implicit conversion) 

 

 

Guess you like

Origin blog.csdn.net/smartgps2008/article/details/90737553