引言
在多线程编程中,线程同步是一个至关重要的话题。C# 提供了多种同步机制,其中 Mutex(互斥体)是一种强大的同步原语,可以跨进程进行线程同步。本文将深入探讨 Mutex 类的 WaitOne 方法,这是使用 Mutex 进行线程同步的核心方法。
Mutex 类简介
Mutex 是 "Mutual Exclusion" 的缩写,它是一种同步原语,用于在多个线程之间提供对共享资源的互斥访问。与 Monitor 和 lock 语句不同,Mutex 可以跨应用程序域、进程甚至机器边界(在命名 Mutex 的情况下)进行同步。
Mutex 的主要特点
| 特点 | 描述 |
|---|---|
| 跨进程同步 | 命名 Mutex 可以在不同进程间共享 |
| 线程亲和性 | 只有获得 Mutex 的线程才能释放它 |
| 递归获取 | 同一线程可以多次获取同一 Mutex |
| 系统资源 | Mutex 是操作系统内核对象,开销相对较大 |
WaitOne 方法详解
WaitOne 是 Mutex 类最重要的方法之一,用于请求 Mutex 的所有权。当线程调用 WaitOne 时,它会阻塞直到获得 Mutex 或超时。
方法重载
WaitOne 方法有多个重载版本:
// 无限期等待
public virtual bool WaitOne();
// 指定超时时间(毫秒)
public virtual bool WaitOne(int millisecondsTimeout);
// 指定超时时间(TimeSpan)
public virtual bool WaitOne(TimeSpan timeout);
// 指定超时时间和是否退出上下文域
public virtual bool WaitOne(int millisecondsTimeout, bool exitContext);
public virtual bool WaitOne(TimeSpan timeout, bool exitContext);返回值说明
- true:成功获得 Mutex 的所有权
- false:在指定的超时时间内未能获得 Mutex
基本使用示例
示例 1:基本的线程同步
using System;
using System.Threading;
class Program
{
private static Mutex mutex = new Mutex();
private static int sharedResource = 0;
static void Main()
{
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++)
{
threads[i] = new Thread(WorkerThread);
threads[i].Name = $"Thread-{i + 1}";
threads[i].Start();
}
foreach (Thread t in threads)
{
t.Join();
}
Console.WriteLine($"Final value: {sharedResource}");
}
static void WorkerThread()
{
for (int i = 0; i < 1000; i++)
{
mutex.WaitOne(); // 获取 Mutex
try
{
sharedResource++;
Console.WriteLine($"{Thread.CurrentThread.Name} incremented to {sharedResource}");
}
finally
{
mutex.ReleaseMutex(); // 释放 Mutex
}
}
}
}示例 2:使用超时机制
using System;
using System.Threading;
class TimeoutExample
{
private static Mutex mutex = new Mutex();
static void Main()
{
Thread t1 = new Thread(LongRunningTask);
Thread t2 = new Thread(TimeoutTask);
t1.Start();
Thread.Sleep(100); // 确保 t1 先获得 Mutex
t2.Start();
t1.Join();
t2.Join();
}
static void LongRunningTask()
{
mutex.WaitOne();
try
{
Console.WriteLine("Long task started");
Thread.Sleep(5000); // 模拟长时间操作
Console.WriteLine("Long task completed");
}
finally
{
mutex.ReleaseMutex();
}
}
static void TimeoutTask()
{
Console.WriteLine("Attempting to acquire mutex with 2 second timeout...");
if (mutex.WaitOne(2000)) // 2秒超时
{
try
{
Console.WriteLine("Successfully acquired mutex");
}
finally
{
mutex.ReleaseMutex();
}
}
else
{
Console.WriteLine("Failed to acquire mutex within timeout period");
}
}
}