⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadsynchdlg.cpp

📁 VC++MFC多线程同步实例,信号量,互斥锁,事件,临界资源,,,,BY GDUT NETWORK 01
💻 CPP
字号:
// ThreadSynchDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ThreadSynch.h"
#include "ThreadSynchDlg.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include <afxmt.h>

HANDLE hSema;
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();
	
	// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA
	
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL
	
	// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CThreadSynchDlg dialog

CThreadSynchDlg::CThreadSynchDlg(CWnd* pParent /*=NULL*/)
: CDialog(CThreadSynchDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CThreadSynchDlg)
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CThreadSynchDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CThreadSynchDlg)
	DDX_Control(pDX, IDC_PROGRESS, m_pos);
	DDX_Control(pDX, IDC_EDIT_SOURCE, m_source);
	DDX_Control(pDX, IDC_EDIT_DESTRINSTION, m_des);
	DDX_Control(pDX, IDC_EDIT_CSECTION, m_resultcs);
	DDX_Control(pDX, IDC_EDITMUTEX, m_resultmu);
	DDX_Control(pDX, IDC_EDIT_EVENT, m_resultev);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CThreadSynchDlg, CDialog)
//{{AFX_MSG_MAP(CThreadSynchDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BTSYNCHEVENT, OnBtsynchevent)
ON_BN_CLICKED(IDC_BTASYNCHEVENT, OnBtasynchevent)
ON_BN_CLICKED(IDC_BTSYNCHMUTEX, OnBtsynchmutex)
ON_BN_CLICKED(IDC_BTASYNCHMUTEX, OnBtasynchmutex)
ON_BN_CLICKED(IDC_BTSYNCHCSECTION, OnBtsynchcsection)
ON_BN_CLICKED(IDC_BTASYNCHCSECTION, OnBtasynchcsection)
ON_BN_CLICKED(IDC_BTBROWSS, OnBtbrowss)
ON_BN_CLICKED(IDC_BTBROWSD, OnBtbrowsd)
ON_BN_CLICKED(IDC_BTCOPY, OnBtcopy)
	ON_BN_CLICKED(IDC_BTCLEAR, OnBtclear)
	ON_BN_CLICKED(IDC_BTEXIT, OnBtexit)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CThreadSynchDlg message handlers

BOOL CThreadSynchDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	
	// Add "About..." menu item to system menu.
	
	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
	
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}
	
	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here
	bmutex=FALSE;
	hSema=CreateSemaphore(NULL,1,1,NULL);
	m_pos.SetRange(0,100);
	m_pos.SetPos(0);
	poslen=0;
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CThreadSynchDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CThreadSynchDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting
		
		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
		
		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;
		
		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CThreadSynchDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

CEvent cEvent;

static UINT threadev1(LPVOID pParam)
{
	CEdit *p=(CEdit*)pParam;
	char buf[MAX_PATH];
	for(int i=0;i<20;i++)
	{
		::SendMessage(p->GetSafeHwnd(),WM_GETTEXT,MAX_PATH,(LPARAM)buf);
		strcat(buf,"A");
		::SendMessage(p->GetSafeHwnd(),WM_SETTEXT,0,(LPARAM)buf);
		Sleep(200);
	}
	return 0;
}
static UINT threadev2(LPVOID pParam)
{
	CEdit *p=(CEdit*)pParam;
	char buf[MAX_PATH];
	for(int i=0;i<20;i++)
	{
		::SendMessage(p->GetSafeHwnd(),WM_GETTEXT,MAX_PATH,(LPARAM)buf);
		strcat(buf,"B");
		::SendMessage(p->GetSafeHwnd(),WM_SETTEXT,0,(LPARAM)buf);
		Sleep(200);
	}
	return 0;
}
static UINT threadev3(LPVOID pParam)
{
	CEdit *p=(CEdit*)pParam;
	char buf[MAX_PATH];
	for(int i=0;i<20;i++)
	{
		::SendMessage(p->GetSafeHwnd(),WM_GETTEXT,MAX_PATH,(LPARAM)buf);
		strcat(buf,"A");
		::SendMessage(p->GetSafeHwnd(),WM_SETTEXT,0,(LPARAM)buf);
		Sleep(200);
	}
	cEvent.SetEvent();
	return 0;
}
static UINT threadev4(LPVOID pParam)
{
	CEdit *p=(CEdit*)pParam;
	char buf[MAX_PATH];
	cEvent.Lock();
	for(int i=0;i<20;i++)
	{
		::SendMessage(p->GetSafeHwnd(),WM_GETTEXT,MAX_PATH,(LPARAM)buf);
		strcat(buf,"B");
		::SendMessage(p->GetSafeHwnd(),WM_SETTEXT,0,(LPARAM)buf);
		Sleep(200);
	}
	cEvent.SetEvent();
	return 0;
}

void CThreadSynchDlg::OnBtsynchevent() 
{
	AfxBeginThread(threadev1,&m_resultev);
	AfxBeginThread(threadev2,&m_resultev);
}

void CThreadSynchDlg::OnBtasynchevent() 
{
	AfxBeginThread(threadev3,&m_resultev);
	AfxBeginThread(threadev4,&m_resultev);
}


CMutex cMutex(FALSE,NULL);

static UINT threadmu1(LPVOID pParam)
{
	CThreadSynchDlg *pdlg=(CThreadSynchDlg*)pParam;
	//char buf[MAX_PATH];
	CString str;
	if(pdlg->bmutex==TRUE)
		cMutex.Lock();
	for(int i=0;i<20;i++)
	{
		pdlg->m_resultmu.GetWindowText(str);
		str+="A";
		pdlg->m_resultmu.SetWindowText(str);
		Sleep(200);
	}
	cMutex.Unlock();
	return 0;
}

static UINT threadmu2(LPVOID pParam)
{
	CThreadSynchDlg *pdlg=(CThreadSynchDlg*)pParam;
	CString str;
	if(pdlg->bmutex==TRUE)
		cMutex.Lock();
	for(int i=0;i<20;i++)
	{
		pdlg->m_resultmu.GetWindowText(str);
		str+="B";
		pdlg->m_resultmu.SetWindowText(str);
		Sleep(200);
	}
	cMutex.Unlock();
	return 0;
}

void CThreadSynchDlg::OnBtsynchmutex() 
{
	bmutex=true;
	AfxBeginThread(threadmu1,this);	
	AfxBeginThread(threadmu2,this);	
	
}

void CThreadSynchDlg::OnBtasynchmutex() 
{
	bmutex=false;
	AfxBeginThread(threadmu1,this);	
	AfxBeginThread(threadmu2,this);	
}

CRITICAL_SECTION hCritial;

static UINT threadcs1(LPVOID pParam)
{
	CThreadSynchDlg *pdlg=(CThreadSynchDlg*)pParam;
	CString str;
	char buf[MAX_PATH];
	if(pdlg->bcritical==TRUE)
		EnterCriticalSection(&hCritial);
	
	for(int i=0;i<20;i++)
	{
		::SendMessage(pdlg->m_resultcs.GetSafeHwnd(), 
			WM_GETTEXT, sizeof(buf)/sizeof(char), (LPARAM)buf);
		strcat(buf,"A");
		UINT len=strlen(buf);
		buf[len]='\0';
		::SendMessage(pdlg->m_resultcs.GetSafeHwnd(),WM_SETTEXT,0,(LPARAM)buf);
		Sleep(200);
	}
	LeaveCriticalSection(&hCritial);
	return 0;
	
}
static UINT threadcs2(LPVOID pParam)
{
	CThreadSynchDlg *pdlg=(CThreadSynchDlg*)pParam;
	CString str;
	char buf[MAX_PATH];
	if(pdlg->bcritical==TRUE)
		EnterCriticalSection(&hCritial);
	
	for(int i=0;i<20;i++)
	{
		::SendMessage(pdlg->m_resultcs.GetSafeHwnd(), 
			WM_GETTEXT, sizeof(buf)/sizeof(char), (LPARAM)buf);
		strcat(buf,"B");
		UINT len=strlen(buf);
		buf[len]='\0';
		::SendMessage(pdlg->m_resultcs.GetSafeHwnd(),WM_SETTEXT,0,(LPARAM)buf);
		Sleep(200);
	}
	LeaveCriticalSection(&hCritial);
	return 0;
}

void CThreadSynchDlg::OnBtsynchcsection() 
{
	bcritical=true;
	InitializeCriticalSection(&hCritial);
	AfxBeginThread(threadcs1,this);
	AfxBeginThread(threadcs2,this);
	
}

void CThreadSynchDlg::OnBtasynchcsection() 
{
	bcritical=false;
	AfxBeginThread(threadcs1,this);
	AfxBeginThread(threadcs2,this);
	
}


void CThreadSynchDlg::OnBtbrowss() 
{
	CFileDialog log(TRUE,"文件","*.*",OFN_HIDEREADONLY,"FILE(*.*)|*.*||",NULL);
	if(log.DoModal()==IDOK)
	{
		sourcename=log.GetPathName();
		filename=log.GetFileName();
		m_source.SetWindowText(sourcename);
	}
	
	
}

void CThreadSynchDlg::OnBtbrowsd() 
{
	if(sourcename.IsEmpty())
		return;
	BROWSEINFO bi;   
	char buffer[MAX_PATH];   
	ZeroMemory(buffer,MAX_PATH);   
	bi.hwndOwner=GetSafeHwnd();   
	bi.pidlRoot=NULL;   
	bi.pszDisplayName=buffer;   
	bi.lpszTitle="选择一个文件夹";   
	bi.ulFlags=BIF_EDITBOX;   
	bi.lpfn=NULL;   
	bi.lParam=0;   
	bi.iImage=0; 
	LPITEMIDLIST pList=NULL;   
	if((pList=SHBrowseForFolder(&bi))!=NULL)   
	{   
		char path[MAX_PATH];
		ZeroMemory(path,MAX_PATH);
		SHGetPathFromIDList(pList,path);
		desname=path;
		if(desname.Right(1)!="\\")
			desname.Format("%s\\%s",path,filename);
		else
			desname.Format("%s%s",path,filename);
		m_des.SetWindowText(desname);
	}
	
}

void CThreadSynchDlg::OnBtsynchsp() 
{
	// TODO: Add your control notification handler code here
	
}

void CThreadSynchDlg::OnBtasynchsp() 
{
	// TODO: Add your control notification handler code here
	
}


static UINT threadsp1(LPVOID pParam)
{
	WaitForSingleObject(hSema,INFINITE);
	CThreadSynchDlg *pdlg=(CThreadSynchDlg*)pParam;
	CString tmp;tmp=pdlg->sourcename;
	CFile* readfile;
	readfile=new CFile(tmp,CFile::modeRead);
	readfile->Seek(pdlg->poslen,CFile::begin);
	pdlg->readlen=readfile->Read(pdlg->pvData,512);
	pdlg->poslen+=pdlg->readlen;
	readfile->Close();
	delete readfile;
	ReleaseSemaphore(hSema,1,NULL);
	return 0;
}
static UINT threadsp2(LPVOID pParam)
{
	WaitForSingleObject(hSema,INFINITE);
	CThreadSynchDlg *pdlg=(CThreadSynchDlg*)pParam;
	CFile* writefile;
	writefile=new CFile(pdlg->desname,CFile::modeWrite);
	writefile->SeekToEnd();
	writefile->Write(pdlg->pvData,pdlg->readlen);
	writefile->Close();
	delete writefile;
	ReleaseSemaphore(hSema,1,NULL);
	return 0;
}


void CThreadSynchDlg::OnBtcopy() 
{
	HANDLE hfile=::CreateFile(desname,GENERIC_WRITE|GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
	CloseHandle(hfile);
	CFileStatus status;
	CFile::GetStatus(sourcename,status);
	filelen=status.m_size;
	//计算文件的百分之一大小
	ldiv_t r;
	r=ldiv(filelen,100);
	long pos=r.quot;
	//保存递增的百分比大小
	long ipos;
	ipos=pos;
	int i=0;
	hGlobal = GlobalAlloc(GMEM_MOVEABLE,512);
	pvData = GlobalLock(hGlobal);
	
	while(1)
	{
		AfxBeginThread(threadsp1,this);
		AfxBeginThread(threadsp2,this);
		if(poslen>ipos)
		{
			ipos+=pos;
			i++;
		}
		m_pos.SetPos(i);
		if(poslen==filelen)
			break;
	}
	GlobalUnlock(hGlobal);
	AfxMessageBox("复制完成");
	
}

void CThreadSynchDlg::OnBtclear() 
{

}

void CThreadSynchDlg::OnBtexit() 
{
	int i;
	this->EndDialog (i);
}

⌨️ 快捷键说明

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