多线程
#include<thread>'
static mutex mu; //互斥锁
class SaleTick
{
public:
void Main(int first)
{
cout << "In SaleTick" << endl;
//互斥锁,尽量晚的加锁,尽量早的解锁
}
};
SaleTick st1;
thread th1(&SaleTick::Main, &st1, 10) //参数一,入口函数; 参数二,对象; 参数三,传递给入口参数的函数(不建议带参数三)
//若对象内有变量需要赋值,可直接 st1.id = 10;这样赋值
th1.detach(); //不再管此线程(大部分使用此情况)
th1.join(); //等待执行结束,是阻塞函数
1 #include<iostream> 2 #include<thread> 3 #include<mutex> 4 #include<unistd.h> 5 6 static int ticks = 100; 7 static std::mutex mu; 8 9 class SaleTick 10 { 11 public: 12 void Main() 13 { 14 std::cout << "In SaleTick" << std::endl; 15 for(;;) 16 { 17 mu.lock(); 18 if(ticks <= 0) 19 { 20 mu.unlock(); 21 break; 22 } 23 ticks--; 24 mu.unlock(); 25 sale ++; 26 usleep(1); 27 } 28 } 29 int sale = 0; 30 }; 31 //#include<unistd.h> 32 //#include<stdlib.h> 33 int main() 34 { 35 36 std::cout << "**********" << std::endl; 37 38 // int p = getpgid(0); 39 // std::cout << p << std::endl; 40 41 SaleTick st1; 42 SaleTick st2; 43 44 std::thread th1(&SaleTick::Main, &st1); 45 std::thread th2(&SaleTick::Main, &st2); 46 //th1.detach(); 47 //th2.detach(); 48 th1.join(); 49 th2.join(); 50 std::cout << "S1 Sale" << st1.sale << std::endl << "S2 Sale" << st2.sale << std::endl; 51 std::getchar(); 52 return 0; 53 }
g++ -std=c++11 main.cpp -lpthread