threadtest.cpp

来自「这是本人在工作中积累的VC++类库」· C++ 代码 · 共 75 行

CPP
75
字号
// threadTest.cpp : 定义控制台应用程序的入口点。
//

#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;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?