zoukankan      html  css  js  c++  java
  • c# 进程间同步实现



     转自msdn 的。。

    // This example shows how a Mutex is used to synchronize access
    // to a protected resource. Unlike Monitor, Mutex can be used with
    // WaitHandle.WaitAll and WaitAny, and can be passed across
    // AppDomain boundaries.
     
    using System;
    using System.Threading;

    class Test
    {
        
    // Create a new Mutex. The creating thread does not own the
        
    // Mutex.
        private static Mutex mut = new Mutex();
        
    private const int numIterations = 1;
        
    private const int numThreads = 3;

        
    static void Main()
        {
            
    // Create the threads that will use the protected resource.
            for(int i = 0; i < numThreads; i++)
            {
                Thread myThread 
    = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name 
    = String.Format("Thread{0}", i + 1);
                myThread.Start();
            }

            
    // The main thread exits, but the application continues to
            
    // run until all foreground threads have exited.
        }

        
    private static void MyThreadProc()
        {
            
    for(int i = 0; i < numIterations; i++)
            {
                UseResource();
            }
        }

        
    // This method represents a resource that must be synchronized
        
    // so that only one thread at a time can enter.
        private static void UseResource()
        {
            
    // Wait until it is safe to enter.
            mut.WaitOne();

            Console.WriteLine(
    "{0} has entered the protected area"
                Thread.CurrentThread.Name);

            
    // Place code to access non-reentrant resources here.

            
    // Simulate some work.
            Thread.Sleep(500);

            Console.WriteLine(
    "{0} is leaving the protected area\r\n"
                Thread.CurrentThread.Name);
             
            
    // Release the Mutex.
            mut.ReleaseMutex();
        }
    }


  • 相关阅读:
    [洛谷P2745] [USACO5.3]窗体面积Window Area
    [洛谷P2751] [USACO4.2]工序安排Job Processing
    [洛谷P2738] [USACO4.1]篱笆回路Fence Loops
    [洛谷P4609] [FJOI2016]建筑师
    [洛谷P3228] [HNOI2013]数列
    解决Qt5使用SSL的“qt.network.ssl: QSslSocket: cannot resolve SSLv2_client_method”错误
    qt查看是否支持SSL
    qt获取依赖的openssl的版本
    qt关闭ssl验证,解决不能正常使用自签署ssl证书API的问题
    使用OpenSSL创建HTTPS所使用的SSL证书
  • 原文地址:https://www.cnblogs.com/gwazy/p/832579.html
Copyright © 2011-2022 走看看