提问人:SP222 提问时间:11/11/2023 更新时间:11/11/2023 访问量:52
唤醒 ThreadPool 中现有线程的问题
The problem of waking up existing threads in the ThreadPool
问:
我需要有关此代码的帮助,因此,如果有人愿意提供帮助,我将不胜感激。
我创建了一个简单的线程池,它传递了一个数字数组,对于每个数字,线程需要计算该数字的阶乘。对我来说有什么问题,如果我创建了一个 2 个线程的线程池,第一个线程将执行第一个任务,第二个线程将执行第二个任务,问题是如果在特定情况下有两个以上的任务,这些线程不会唤醒执行所有任务, 问题是我不知道如何重新唤醒线程,以及如何让它们在有任务的情况下继续执行任务?
这是我的代码:
MyThreadPool 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThreadPool
{
public class MyThreadPool
{
private bool _disposed = false;
private object _lock = new object();
private Queue<MyTask> tasks = new();
private List<Thread> threads = new();
public MyThreadPool(int numThreads = 0)
{
for (int i = 0; i < numThreads; i++)
{
new Thread(() =>
{
threads.Add(Thread.CurrentThread);
if (_disposed == false)
{
MyTask task = null;
lock (_lock)
{
if (tasks.Count > 0)
{
task = tasks.Dequeue();
}
else
_disposed = true;
if (task != null)
{
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} calculated factorial for {task.getNum()}. Result: {task.CalculateFactoriel(task.getNum())}");
Thread.Sleep(1000);
}
else
{
Thread.Sleep(1000);
}
}
}
}).Start();
}
}
public void Enqueue(int number)
{
tasks.Enqueue(new MyTask(number));
}
public void Dispose()
{
if (_disposed == true)
{
foreach (Thread thread in threads)
{
thread.Join();
}
}
}
}
}
MyTask 类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThreadPool
{
public class MyTask
{
private int num;
public void setNum(int num)
{
this.num = num;
}
public int getNum()
{
return this.num;
}
public MyTask(int number)
{
this.num = number;
}
public int CalculateFactoriel(int number)
{
int result = 1;
for (int i = number; i > 0; i--)
{
result = result * i;
}
return result;
}
}
}
程序.cs:
int[] array = { 1, 2, 3, 4, 5, 6 };
int numThread = 2;
int x = 0;
MyThreadPool threadPool = new(numThread);
for (int i = 0; i < array.Length; i++)
{
threadPool.Enqueue(array[i]);
}
while (x != array.Length) ;
threadPool.Dispose();
答: 暂无答案
上一个:如何在 C# 中使用线程同时执行存储过程 [已关闭]
下一个:与程序同时运行表单
评论
_disposed = true;
threads.Add(Thread.CurrentThread);