VC++ Mutex

来源:互联网 发布:淘宝卖电子书 编辑:程序博客网 时间:2024/05/23 23:12

声明:本人一个菜鸟,网上搜罗了很多关于VC++编程的资料,可每本资料都是涵盖面太广,难以细致。英语又太烂,所以不得意只得摸索,恐又忘记所以记在此处,若有不对的地方,烦劳指出,不胜感激。

author:fym0121@163.com

license:GPL

IDE:Visual Studio 2008


进程alice

#include "stdafx.h"#include <iostream>#include <Windows.h>#include <process.h>int _tmain(int argc, _TCHAR* argv[]){    std::cout << "Begin All pro_alice" <<std::endl;    TCHAR szMutex[]= _T("mutex_pro");    HANDLE g_hMutex = CreateMutex(NULL,        FALSE,             //新建Mutex不被任何线程占有        szMutex);    TCHAR szProName[] = _T("pro_bob.exe");    PROCESS_INFORMATION pi;    STARTUPINFO si = {sizeof(si)};    CreateProcess(NULL,   //这新建进程的可执行文件,可以为NULL        szProName,        //参数信息,一般将可执行文件名,参数都放到这,可写        NULL,             //进程安全属性        NULL,             //线程安全属性        FALSE,            //是否继承内核对象        0,                //标志        NULL,             //环境变量        NULL,             //工作目录        &si,              //不能为空        &pi               //不能为空        );    Sleep(3000);    WaitForSingleObject(g_hMutex,INFINITE);    // do ...    ReleaseMutex(g_hMutex);    WaitForSingleObject(pi.hProcess,INFINITE);    std::cout << "End pro_alice" <<std::endl;return 0;}

进程bob

#include "stdafx.h"#include <iostream>#include <Windows.h>#include <process.h>int _tmain(int argc, _TCHAR* argv[]){    std::cout << "Begin All pro_bob" <<std::endl;    TCHAR szMutex[]= _T("mutex_pro");    HANDLE g_hMutex = CreateMutex(NULL,TRUE,szMutex);    WaitForSingleObject(g_hMutex,INFINITE);    ReleaseMutex(g_hMutex);       std::cout << "End pro_bob" <<std::endl;return 0;}


原创粉丝点击