Last active
July 27, 2018 07:44
-
-
Save oscar60310/5a93e9ff5d3c593bef35e919ab1aa313 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
void Calculate(Result res, String thread) | |
{ | |
while (res.Add < 1000) | |
{ | |
lock (res) | |
{ | |
if (res.Add < 1000) | |
{ | |
Console.WriteLine($"{thread}({Thread.CurrentThread.ManagedThreadId}): {res.Add}"); | |
res.Answer += (++res.Add); | |
} | |
} | |
Thread.Sleep(10); | |
} | |
}; | |
var Res = new Result(); | |
var workers = new List<Task>(); | |
for(var i = 0; i < 10; i++) | |
{ | |
workers.Add(Task.Factory.StartNew((name) => Calculate(Res, $"C{name}"), i)); | |
} | |
Task.WaitAll(workers.ToArray()); | |
Console.Write($"Finish {Res.Answer}"); | |
Console.ReadKey(); | |
} | |
class Result | |
{ | |
public int Answer = 0; | |
public int Add = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment