溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#多進(jìn)程間信號(hào)量同步

發(fā)布時(shí)間:2024-09-13 16:52:44 來(lái)源:億速云 閱讀:79 作者:小樊 欄目:編程語(yǔ)言

在C#中,可以使用System.Threading.Semaphore類來(lái)實(shí)現(xiàn)多進(jìn)程間的信號(hào)量同步。信號(hào)量是一種同步原語(yǔ),用于控制對(duì)共享資源的訪問(wèn)。它允許多個(gè)進(jìn)程或線程同時(shí)訪問(wèn)資源,但會(huì)限制同時(shí)訪問(wèn)的數(shù)量。

下面是一個(gè)簡(jiǎn)單的示例,展示了如何在C#中使用信號(hào)量實(shí)現(xiàn)多進(jìn)程間的同步:

  1. 首先,創(chuàng)建一個(gè)名為SemaphoreExample的控制臺(tái)應(yīng)用程序項(xiàng)目。

  2. Program.cs文件中,編寫以下代碼:

using System;
using System.Diagnostics;
using System.Threading;

namespace SemaphoreExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創(chuàng)建一個(gè)名為"MySemaphore"的信號(hào)量,初始值為3,最大值為5
            using (Semaphore semaphore = new Semaphore(3, 5, "MySemaphore"))
            {
                // 啟動(dòng)5個(gè)子進(jìn)程
                for (int i = 0; i < 5; i++)
                {
                    Process process = new Process();
                    process.StartInfo.FileName = "SemaphoreChildProcess.exe";
                    process.StartInfo.Arguments = i.ToString();
                    process.Start();
                }

                // 等待所有子進(jìn)程退出
                while (true)
                {
                    int currentCount = semaphore.Release();
                    if (currentCount == 3)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
            }
        }
    }
}
  1. 創(chuàng)建一個(gè)名為SemaphoreChildProcess的新控制臺(tái)應(yīng)用程序項(xiàng)目。

  2. Program.cs文件中,編寫以下代碼:

using System;
using System.Threading;

namespace SemaphoreChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            // 獲取傳入的參數(shù)
            int processId = int.Parse(args[0]);

            // 打開名為"MySemaphore"的信號(hào)量
            using (Semaphore semaphore = Semaphore.OpenExisting("MySemaphore"))
            {
                // 請(qǐng)求信號(hào)量
                semaphore.WaitOne();

                Console.WriteLine($"Process {processId} is running.");
                Thread.Sleep(2000); // 模擬資源訪問(wèn)
                Console.WriteLine($"Process {processId} has finished.");

                // 釋放信號(hào)量
                semaphore.Release();
            }
        }
    }
}
  1. SemaphoreChildProcess項(xiàng)目設(shè)置為啟動(dòng)項(xiàng)目,并運(yùn)行。你將看到5個(gè)子進(jìn)程按順序運(yùn)行,每次只有3個(gè)子進(jìn)程同時(shí)運(yùn)行。這是因?yàn)槲覀儎?chuàng)建了一個(gè)初始值為3的信號(hào)量,限制了同時(shí)訪問(wèn)資源的進(jìn)程數(shù)量。
向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI