24,854
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <iostream>
#include <string>
#include <conio.h>
#include <Thread.h> //in libmoxu
#include <CriticalSection.h> //in libmoxu
using namespace std;
using namespace moxu;
CriticalSection cs;
void fun()
{
int c = 10;
while(c--)
{
ScopedLock locker(cs); //加锁,离开作用域时自动解锁
cout<<"fun: c="<<c<<endl;
Sleep(100);
}
}
class Test
{
public:
void Fun()
{
int c = 10;
while(c--)
{
ScopedLock locker(cs);
cout<<"Test::Fun: c="<<c<<endl;
Sleep(100);
}
}
};
int main()
{
Thread th1;
Thread th2;
Test test;
{
ScopedLock locker(cs);
cout<<"start thread 1"<<endl;
}
th1.Start(fun);
{
ScopedLock locker(cs);
cout<<"start thread 2"<<endl;
}
th2.Start(Bind(&test, Test::Fun));
cout<<"wait..."<<endl;
th1.Join();
th2.Join();
cout<<"threads end! press any key to continue"<<endl;
getch();
return 0;
}