问题描述
准备写个Lib,实现对文件的读写互斥,用什么互斥机制比较好啊,我准备用Mutex,但怎么定义它呢,在程序里直接create的话,每当其他进程访问到这段代码时,再执行createmutex不会有影响么,求教
解决方案
解决方案二:
看看MSDN上的例子吧:usingSystem;usingSystem.Threading;classTest{//CreateanewMutex.Thecreatingthreaddoesnotownthe//Mutex.privatestaticMutexmut=newMutex();privateconstintnumIterations=1;privateconstintnumThreads=3;staticvoidMain(){//Createthethreadsthatwillusetheprotectedresource.for(inti=0;i<numThreads;i++){ThreadmyThread=newThread(newThreadStart(MyThreadProc));myThread.Name=String.Format("Thread{0}",i+1);myThread.Start();}//Themainthreadexits,buttheapplicationcontinuesto//rununtilallforegroundthreadshaveexited.}privatestaticvoidMyThreadProc(){for(inti=0;i<numIterations;i++){UseResource();}}//Thismethodrepresentsaresourcethatmustbesynchronized//sothatonlyonethreadatatimecanenter.privatestaticvoidUseResource(){//Waituntilitissafetoenter.mut.WaitOne();Console.WriteLine("{0}hasenteredtheprotectedarea",Thread.CurrentThread.Name);//Placecodetoaccessnon-reentrantresourceshere.//Simulatesomework.Thread.Sleep(500);Console.WriteLine("{0}isleavingtheprotectedarearn",Thread.CurrentThread.Name);//ReleasetheMutex.mut.ReleaseMutex();}}
解决方案三:
何必用Mutex呢?FileStream本身就支持读写互斥:FileStreamfs=newFileStream("...",FileMode.Open,FileAccess.Read,FileShare.Read);StreamReadersr=newStreamReader(fs);//...你用Mutex控制,那些不用Mutex的进程一样可以绕过你的控制。
解决方案四:
我想让多个进程调用这个lib,进行文件的读写互斥这样的话FileStream就不行了吧?
解决方案五:
引用3楼rambooo的回复:
我想让多个进程调用这个lib,进行文件的读写互斥这样的话FileStream就不行了吧?
Whynot?Didyoutryit?MSDN
FileShare.None:Declinessharingofthecurrentfile.Anyrequesttoopenthefile(bythisprocessoranotherprocess)willfailuntilthefileisclosed.