cdb*_*a89 6 c# multithreading semaphore locks
我有几个继承自ClassA的对象,它有一个抽象方法MethodA.
这些继承对象中的每一个都可以同时允许特定数量的线程进入其MethodA.
catch:线程只能在对象的MethodA中,而没有其他对象的MethodA同时被处理.
我怎么解决这个问题?我正在考虑使用信号量,但不知道该怎么做,因为我无法完全解决问题以获得解决方案.
编辑:
示例代码(可能包含语法错误:)
public class ClassA
{
public virtual void MethodA{}
}
public class OneOfMySubclassesOfClassA // there can be multiple instances of each subclass!
{
public override void MethodA{
// WHILE any number of threads are in here, THIS MethodA shall be the ONLY MethodA in the entire program to contain threads
EDIT2: // I mean: ...ONLY MethodA of a subclass (not of a instance of a subclass) in the entire program...
}
}
...and more subclasses...
Run Code Online (Sandbox Code Playgroud)
派生类型与静态信号量一起用作基类中的类型参数,以获得在每个子类的所有实例之间共享的一个信号量。然后会出现一些混乱,以确保只有一种类型处于活动状态。快速测试表明这可以正常工作,但存在问题。
例如,假设当前正在执行 的方法ClassA1。如果执行该方法的新请求频繁到达,则可能会发生其他派生类没有机会执行的情况,因为不断有新线程执行该类的方法ClassA1。
internal abstract class ClassA<TDerived> : ClassA
{
private const Int32 MaximumNumberConcurrentThreads = 3;
private static readonly Semaphore semaphore = new Semaphore(ClassA<TDerived>.MaximumNumberConcurrentThreads, ClassA<TDerived>.MaximumNumberConcurrentThreads);
internal void MethodA()
{
lock (ClassA.setCurrentlyExcutingTypeLock)
{
while (!((ClassA.currentlyExcutingType == null) || (ClassA.currentlyExcutingType == typeof(TDerived))))
{
Monitor.Wait(ClassA.setCurrentlyExcutingTypeLock);
}
if (ClassA.currentlyExcutingType == null)
{
ClassA.currentlyExcutingType = typeof(TDerived);
}
ClassA.numberCurrentlyPossiblyExecutingThreads++;
Monitor.PulseAll(ClassA.setCurrentlyExcutingTypeLock);
}
try
{
ClassA<TDerived>.semaphore.WaitOne();
this.MethodACore();
}
finally
{
ClassA<TDerived>.semaphore.Release();
}
lock (ClassA.setCurrentlyExcutingTypeLock)
{
ClassA.numberCurrentlyPossiblyExecutingThreads--;
if (ClassA.numberCurrentlyPossiblyExecutingThreads == 0)
{
ClassA.currentlyExcutingType = null;
Monitor.Pulse(ClassA.setCurrentlyExcutingTypeLock);
}
}
}
protected abstract void MethodACore();
}
Run Code Online (Sandbox Code Playgroud)
请注意,包装器方法用于调用 中的实际实现MethodACore。所有派生类之间共享的所有同步对象都位于非泛型基类中。
internal abstract class ClassA
{
protected static Type currentlyExcutingType = null;
protected static readonly Object setCurrentlyExcutingTypeLock = new Object();
protected static Int32 numberCurrentlyPossiblyExecutingThreads = 0;
}
Run Code Online (Sandbox Code Playgroud)
派生类将如下所示。
internal sealed class ClassA1 : ClassA<ClassA1>
{
protected override void MethodACore()
{
// Do work here.
}
}
internal sealed class ClassA2 : ClassA<ClassA2>
{
protected override void MethodACore()
{
// Do work here.
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我现在没有时间更详细地解释它是如何以及为什么起作用的,但我明天会更新答案。