C++ 11 thread 基础用法 lock unlock join mutex joinable lock_guard unique_lock condition_variable wait notify_one notify_all asnyc future packaged_task promise

#include "pch.h"
#include<iostream>
#include<string>
#include<vector>
#include<list>
// 线程相关头文件
#include<thread>
#include<mutex>
#include<future>
using namespace std;

static int res = 0; // demonstrate the use of the shared variable write mutex.

mutex my_mutex; // mutex
the mutex my_mutex2;
void Test () // without parameters
{
Auto ID = this_thread :: get_id ();
COUT << "= no parameter ID" << endl << ID;
/ * Mutual the amount of protected data repellent lock and unlock the form * /
my_mutex.lock ();
// lock (my_mutex, my_mutex2); equivalent to simultaneously lock all the mutex
RES =. 1;
my_mutex.unlock (); // into pairs Correct.
return;
}
void test2 (int)
{
Auto ID = this_thread :: get_id ();
COUT << "arguments = ID" << endl << ID;
/ *
mutex lock_guard form of data protection.
Parameters adopt_lock (target structure) action is a mutex lock has a.
* /
Lock_guard <the mutex> my_lock (my_mutex); // lock_guard <the mutex> my_lock (my_mutex, adopt_lock);.
2 = RES;
return;


{
Public:
void operator () () // not with parameters
{
Auto ID = this_thread :: get_id ();
COUT << "= class object ID" << endl << ID;
return;
}
// of call_once
static void Once ()
{
return;
}
};
void sECOND ()
{
return;
}
void my_async ();
void my_packaged ();
void my_promise_ ();
int main ()
{
int TEMP;
Thread my_thread (Test);
// first callable object parameters, including functions, classes (to be defined () operator overloading), the lambda expression, subsequent parameters as a function of the corresponding parameters.
my_thread2 the Thread (test2, the TEMP);
// wait for the Join the child thread is finished and then back to the main thread

if (my_thread.joinable ()) // joinable determines whether the child thread join / the detach
{
my_thread.join ();
}
// once a thread can join
my_thread2.join ();
/ * the detach without waiting for a child thread (as far as possible not used)
my_thread.detach ();
my_thread2.detach ();
* /
A A;
Thread my_thread3 (A);
my_thread3.join ();

// call_once () includes a mutex capacity to ensure that the function is performed only once and more efficient. Requires a combination of marker once_flag (also a structure) using
once_flag g_flag;
once_flag p_flag;
of call_once (g_flag, A :: Once);
of call_once (p_flag, SECOND);
// related to the async Future.
my_async ();
my_packaged ();
my_promise_ ();
COUT << "! the I Love China" << endl;
return 0;
}

// more flexible unique_lock class template. Can replace lock_guard you do not need to unlock the second parameter has adopt_lock (with lock_guard, provided that the first lock)


// try_to_lock (the premise is not to lock, do not block the thread.)

// defer_lock (the premise is not to lock, initialize an unlocked mutex) member function can be called directly.

// member function lock ()

//unlock()

// try_lock () my_unique. try_lock () == true representation to get the lock, the lock did not get other things to dry.

// release () Returns the pointer to the object and release ownership of the mutex mutex * ptr = my_unique.release (); ptr-> unlock ();

// unique_lock <mutex> my_unique (my_mutex) fewer lock code, the finer the particle size.

// unique_lock <mutex> my_unique2 (move :: my_unique) // transfer of ownership

/*------------------------------------------------------------------------------

condition_variable wait() notify_one notify_all

condition_variable my_cond generation condition variable object, need to work with the mutex

wait wait wait notify_one wake wake up all notify_all

------------------------------------------------------------------------------*/

condition_variable my_cond;
mutex my_mutex3;
bool juge()
{
if (true)
{
return true;
}
return false;
}

outmsg void ()
{
int Command = 0;
the while (to true)
{
unique_lock is <the mutex> my_mu (my_mutex3);
my_cond.wait (my_mu, JUGE);

// second parameter returns false then unlocks the mutex, and clog, until another thread calls notify_once () member function so far.
// The second parameter default is false

// meal operation. . .

// missing can be prevented subsequent operation conditions (such as a shared message queue can not read the message without the need to wait a write operation to write data.)

//mes.pop_back () reads the first message.

break;
}
}

inMsg void ()
{
for (int I = 0; I <100000; I ++)
{
unique_lock is <the mutex> my_mu (my_mutex3);
// meal operation
my_cond.notify_one (); // try to wake-wait () mutex lock after he is released.

// notify_all () wakes up all the wait ();
}

}
/*------------------------------------------------------------------------------

async start an asynchronous tasks (automatically create a thread) and returns the value, return to future class template.

future provide access to asynchronous operation returns the result of the mechanism.

packaged_task wrapper function

promise class template, in a thread assignment, extracting promise <int> my_promise in another thread;

------------------------------------------------------------------------------*/

int mythread()
{
auto id = this_thread::get_id();
cout << "async 的 id=" << id << endl;
//使线程睡觉5秒
chrono::milliseconds dura(5000);
this_thread::sleep_for(dura);
cout << "async 的 id=" << id << endl;
return 5;
}

my_async void ()
{
// Future <int> Result = async (MyThread);
// default parameters without waiting for the async.
future <int> result = async ( launch :: deferred, mythread); // call the future if it is a member function of class <int> result = async (& A :: mythread, & Aobj, member function parameters);

// asnyc can accept additional parameters enumerated type std :: launch

// deferred to delay calling until you call the get () and wait () thread before execution, if not these two functions, the thread will not be created.

<< cout "the Continue ....." << endl;
cout << "the Continue ....." << endl;
cout << "the Continue ....." << endl;
cout << "the Continue ..... "<< endl;
// use get () returns the thread results. Do not get the return value dogged.
cout << "async result returned =" << result.get () << endl;
return;
}
int mythread1 (int MYPT)
{
return MYPT;
}

void my_packaged()
{
packaged_task<int(int)>mypt(mythread1);

/ * Lambda expression
packaged_task <int (int)> MYPT ([] (int MyPar)
{

}
); * /

thread my_pt(ref(mypt), 1);
my_pt.join();
future<int>res = mypt.get_future();
cout << "packaged返回结果:"<<res.get() << endl;
return;
}

my_promise void (promise <int> TEMP &, int CUR)
{
CUR ++;
CUR = 10 *;
int Result = CUR; // save the result
temp.set_value (result); // result is placed into the promise

}

void my_promise_()
{
promise<int>myprom;
thread t(my_promise, ref(myprom), 10);
t.join();
future<int>fu = myprom.get_future();
int result=fu.get();
cout << "promise结果=" << result<<endl;
return;
}

Guess you like

Origin www.cnblogs.com/yangshengjing/p/11621238.html