假设你正在运行一个像IMDb/Netflix这样的电影数据库网站,用户可以评价1-10星级的每部电影.当用户评价电影时,我在请求中得到id(长)并且评分为1-10.Movie类看起来像这样.
class Movie
{
long id;
String name;
double avgRating; //Avg Rating of this movie
long numberOfRatings; //how many times this movie was rated.
}
public void updateRating(long movieId, int rating)
{
//code to update movie rating and update top 10 movie to show on page.
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我可以选择将大量电影数据保存在内存中的数据结构,以便在每次updateRating调用时,我更新电影评级以及更新前10部电影并反映在网页上,用户将始终看到最新的前10部电影.我在Web服务器上有很多空间,我可以将所有电影对象保存在内存中.这里的挑战是
1)通过id查找电影.
2)更新电影评级.
3)在已分类的电影集中选择此电影的新位置(按评级排序),如果其新位置位于前10位,则在网页上显示.
所有这些操作都应在最佳的最佳时间内完成.
这不是一个家庭作业,而是一般的编程和数据结构问题.
我试图了解如何在.Net中实现Parallelism.以下代码以Reed Copsey Blog为例.
此代码循环遍历客户集合,并在上次联系后的14天后向他们发送电子邮件.我的问题是,如果客户表非常大并且发送电子邮件需要几秒钟,这个代码不会将CPU拒绝服务模式带到其他重要流程吗?
有没有办法并行运行以下代码行,但只使用少量内核,以便其他进程可以共享CPU?或者我是以错误的方式解决问题?
Parallel.ForEach(customers, (customer, parallelLoopState) =>
{
// database operation
DateTime lastContact = theStore.GetLastContact(customer);
TimeSpan timeSinceContact = DateTime.Now - lastContact;
// If it's been more than two weeks, send an email, and update...
if (timeSinceContact.Days > 14)
{
// Exit gracefully if we fail to email, since this
// entire process can be repeated later without issue.
if (theStore.EmailCustomer(customer) == false)
parallelLoopState.Break();
else
customer.LastEmailContact = DateTime.Now;
}
});
Run Code Online (Sandbox Code Playgroud)
一般承认的答案:
思维过程是正确的!正如Cole Campbell指出的那样,通过在此特定示例中指定ParallelOption对象,可以控制和配置应该使用多少个核心.这是怎么回事.
var parallelOptions = new …Run Code Online (Sandbox Code Playgroud) 我一个接一个地运行了一些时间\ CPU密集型进程(TimeExpensive类型).主线程(A)异步启动另一个线程(B)中的TimeExpensive进程并变为非活动状态.在完成时,线程B同步触发调用者的完成处理程序并在线程B中启动下一个TimeExpensive过程.创建一个新线程(C)但在启动C之后,B完成.因此,对于n个进程,创建了n个线程,并且大部分时间它们不共存.
人们可能希望以线性单线程方式实现它,但TimeExpensive由第三方实现,并且在运行时,它使用所有系统核心并运行数小时.
//This will run as console app
class Program
{
static void Main(string[] args)
{
new Program().StartJobs();
}
void StartJobs()
{
Main mainJob = new Main();
mainJob.MainCompletionEvent +=
new Action<object, EventArgs>(mainJob_MainCompletionEvent);
mainJob.Start();
}
void mainJob_MainCompletionEvent(object sender, EventArgs e)
{
//if(success) Environment.Exit(0);
}
}
class Main
{
int processCounter = 0;
public event Action<object, EventArgs> MainCompletionEvent;
public void Start()
{
//...do other important tasks here...
processCounter++;
TimeExpensive te = new TimeExpensive();
te.CompletionEvent += new Action(TimeExpensive_CompletionHandler);
Thread aThread = new …Run Code Online (Sandbox Code Playgroud)