#include "iostream"
#include "thread"
#include "mutex" //c++11提供的互斥鎖 跨平臺
using namespace std;
int g_iticket = 100;
void bar(void);
void bar1(void);
std:: mutex mx;
int main(void)
{
thread t1(bar);
thread t2(bar1);
t1.join(); //主線程等子線程
t2.join();
return 0;
}
void bar(void)
{
while (true)
{
//mx.lock(); //不借助lock_guard和unique_lock
//lock_guard<mutex>guard(mx);//鎖衛視不需要自己lock 自己的生命週期自己管理 構造出來的是時候 自動調用lock 析構後再自己調用unlock
unique_lock<mutex>unique(mx);//和鎖衛視差不多,但可以自己改變自己的生命週期,提前釋放鎖
if (g_iticket > 0)
{
//mx.unlock();
unique.unlock();//和lock_guard一樣自動lock和unlock 但是可以提前結束自己的生命週期
this_thread::sleep_for(chrono::microseconds(80));
cout << "#" << 1 << ":" << g_iticket-- << endl;
}
else
{
//mx.unlock();
break;
}
}
}
void bar1(void)
{
while (true)
{
//mx.lock();
unique_lock<mutex>unique(mx);//和鎖衛視差不多,但可以自己改變自己的生命週期
if (g_iticket > 0)
{
this_thread::sleep_for(chrono::microseconds(80));
cout << "#" << 2 << ":" << g_iticket-- << endl;
//mx.unlock();
}
else
{
//mx.unlock();
break;
}
}
}
/***************************************************下面是lambda表達式基礎語法及結合線程的使用***********************************/
/*lambda表達式主要解決在函數裏面不能定義函數的問題-------多用於多線程網絡*/
主要語法就是()[] {}
#include<iostream>
#include<functional>
using namespace std;
void foo(void);
function<int(int, int)> foo1(void);
int main(void)
{
foo();
cout << foo1()(4, 5);//四五對應的是傳過去的a,b
return 0;
}
//-------------------------------------------------------------------------------------
void foo(void)
{
int c = 9;
int m=[c](int a,int b/*由下面的5,6傳進來*/)->int/*返回值*/{
return a + b + c;
}(5,6);
int e = 7;
int m=[=,&c](int a,int b/*由下面的5,6傳進來*/)->int/*返回值*/{
//[=,&c]的意思是除了c按引用傳遞之外,其他變量都按值傳遞
c = c + 2;
return a + b + c + e;
}(5,6);
//-----另一種調用方式和傳參-------------------------------------
/*auto lambdas = [c](int a ,int b)->int {
return a + b + c;
};
//-----另一種調用方式和傳參-------------------------------------
cout << lambdas(5,6)<< endl;*/
function < int(int ,int)>lambdas = [=/*捕獲外界所有變量*/](/*傳入的參數*/int a,int b)->int/*返回值*/ {
return a + b + c;
};
cout << lambdas(5, 6);
}
//-------------------------------------------------------------------------------------
function<int(int, int)> foo1(void)
{
int c = 9;
int m =10;
function<int(int, int)>lambdas=[=](int a, int b)->int {
return a + b + c;
};
return lambdas;
}
std::mutex mx
int main(void)
{
//結合c11線程使用
int num=1;
thread t1([=](void)->void{
while (true)
{
lock_guard<mutex>guard(mx);
if (g_iticket > 0)
{
this_thread::sleep_for(chrono::microseconds(80));
cout << "#" << num << ":" << g_iticket-- << endl;
}
else
{
break;
}
}
});
return 0;
}