Windows上多线程同步相关的MFC类(2)

来源:互联网 发布:上海python培训班 编辑:程序博客网 时间:2024/05/15 08:15
转载请标明出处:http://blog.csdn.net/zhangxingping

Windows上多线程同步相关的MFC类(2)

CMutex

在http://blog.csdn.net/zhangxingping/article/details/8512113中提到了“如果多个程序可以访问资源,则可以使用CMutex;否则,使用CCriticalSection。”前面也看到了关于CCriticalSection的使用方法:在同一个程序的多个线程间进行同步控制。实际上,在这种情况下,CCriticalSection比CMutex的效率更高。但是CMutex是可以在多个程序间进行同步控制的。

 

在下面的示例中存在两个程序:它们向同一个文件中写入数据,为了保证每个程序写入数据的完整性就使用到了CMutex。运行时,可以先后一次运行这两个程序,可以看到在一个程序写入数据的时候,另外一个程序是处于等待状态的,直到第一个程序写入数据结束,并进行了Unlock操作。

第一个程序:

//CMutexDemoApp1.cpp : 定义控制台应用程序的入口点。// #include "stdafx.h"#include "CMutexDemoApp1.h" #include "afxmt.h" #ifdef _DEBUG#define new DEBUG_NEW#endif  // 唯一的应用程序对象 CWinApp theApp; using namespacestd; LPCTSTR mutexName = _T("MyMutexDemo"); CMutex mutex(true, mutexName);  int _tmain(intargc,TCHAR*argv[],TCHAR*envp[]){    int nRetCode = 0;     // 初始化MFC并在失败时显示错误    if (!AfxWinInit(::GetModuleHandle(NULL),NULL, ::GetCommandLine(), 0))    {        // TODO: 更改错误代码以符合您的需要        _tprintf(_T("错误: MFC初始化失败\n"));        nRetCode= 1;    }    else    {        // TODO: 在此处为应用程序的行为编写代码。        mutex.Lock();         CFilefile;        cout<<"Trying to open file..." <<endl;        if ( 0== file.Open(_T("c:\\test.txt"),CFile::modeWrite))        {            cout<< "File to open file!";            return0;        }         file.SeekToEnd();          cout<<"Trying to write data..." <<endl;        char buffer[]="A A A A A A A \r\n";        for ( int i = 0; i <= 10; i+=2)        {              file.Write(buffer,sizeof(buffer));            Sleep(2000);        }        file.Close();         mutex.Unlock();     }     return nRetCode;}

第二个程序:

//CMutexDempApp2.cpp : 定义控制台应用程序的入口点。// #include "stdafx.h"#include "CMutexDempApp2.h" #ifdef _DEBUG#define new DEBUG_NEW#endif  #include "afxmt.h" // 唯一的应用程序对象 CWinApp theApp; LPCTSTR mutexName = _T("MyMutexDemo"); CMutex mutex(true, mutexName); using namespacestd; int _tmain(intargc,TCHAR*argv[],TCHAR*envp[]){    int nRetCode = 0;     // 初始化MFC并在失败时显示错误    if (!AfxWinInit(::GetModuleHandle(NULL),NULL, ::GetCommandLine(), 0))    {        // TODO: 更改错误代码以符合您的需要        _tprintf(_T("错误: MFC初始化失败\n"));        nRetCode= 1;    }    else    {        // TODO: 在此处为应用程序的行为编写代码。        mutex.Lock();         CFilefile;        cout<< "Trying to open file..."<< endl;        if ( 0== file.Open(_T("c:\\test.txt"),CFile::modeWrite))        {            cout<< "File to open file!";            return0;        }         file.SeekToEnd();         char buffer[]="B B B B B B B \r\n";         cout<< "Trying to write data..."<< endl;        for ( int i = 0; i <= 10; i+=2)        {              file.Write(buffer,sizeof(buffer));            Sleep(2000);        }        file.Close();         mutex.Unlock();    }     return nRetCode;}

如果去掉上面两个程序中的CMutex的使用,第二个被运行的程序会因为open操作失败而退出的。可见,使用CMutex可以实现多个程序见的同步控制。