C#多进程间信号量同步

发布时间:2024-09-13 16:52:44 作者:小樊
来源:亿速云 阅读:79

在C#中,可以使用System.Threading.Semaphore类来实现多进程间的信号量同步。信号量是一种同步原语,用于控制对共享资源的访问。它允许多个进程或线程同时访问资源,但会限制同时访问的数量。

下面是一个简单的示例,展示了如何在C#中使用信号量实现多进程间的同步:

  1. 首先,创建一个名为SemaphoreExample的控制台应用程序项目。

  2. Program.cs文件中,编写以下代码:

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

namespace SemaphoreExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个名为"MySemaphore"的信号量,初始值为3,最大值为5
            using (Semaphore semaphore = new Semaphore(3, 5, "MySemaphore"))
            {
                // 启动5个子进程
                for (int i = 0; i < 5; i++)
                {
                    Process process = new Process();
                    process.StartInfo.FileName = "SemaphoreChildProcess.exe";
                    process.StartInfo.Arguments = i.ToString();
                    process.Start();
                }

                // 等待所有子进程退出
                while (true)
                {
                    int currentCount = semaphore.Release();
                    if (currentCount == 3)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
            }
        }
    }
}
  1. 创建一个名为SemaphoreChildProcess的新控制台应用程序项目。

  2. Program.cs文件中,编写以下代码:

using System;
using System.Threading;

namespace SemaphoreChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获取传入的参数
            int processId = int.Parse(args[0]);

            // 打开名为"MySemaphore"的信号量
            using (Semaphore semaphore = Semaphore.OpenExisting("MySemaphore"))
            {
                // 请求信号量
                semaphore.WaitOne();

                Console.WriteLine($"Process {processId} is running.");
                Thread.Sleep(2000); // 模拟资源访问
                Console.WriteLine($"Process {processId} has finished.");

                // 释放信号量
                semaphore.Release();
            }
        }
    }
}
  1. SemaphoreChildProcess项目设置为启动项目,并运行。你将看到5个子进程按顺序运行,每次只有3个子进程同时运行。这是因为我们创建了一个初始值为3的信号量,限制了同时访问资源的进程数量。
推荐阅读:
  1. 怎么使用Python3.8
  2. 并发编程中Future机制的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:多进程C#在分布式系统中的角色

下一篇:多进程C#与内存映射文件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》