class Task { public byte[] sharedData; public DateTime day; public void Run() { ... do the processing here, using the shared data and the day ... } }
class ToDoList { public byte[] sharedData; List<Task> toDoList; public void Go() { // Fill the to-do list with a task for every day in the year toDoList = new List<Task>(); for (DateTime d = new DateTime(2008, 1, 1); d.Year == 2008; d = d.AddDays(1)) { Task t = new Task(); t.day = d; // The one particular day we want t.sharedData = sharedData; // The year's worth of data toDoList.Add(t); // Add the task to the to-do list } // Run 2 threads per logical processor (a physical cpu with // hyperthreading enabled counts as 2 logical processors) Thread[] threads = new Thread[Environment.ProcessorCount * 2]; for (int t = 0; t < threads.Length; t++) { threads[t] = new Thread(Runner); // Make the new thread threads[t].Start(); // Start it running } // Wait for the threads to finish all the tasks for (int t = 0; t < threads.Length; t++) { threads[t].Join(); } } /// <summary> /// This is the thread runner that does the work /// It basically eats its way through the to-do list, /// returning when there's nothing left on the list. /// </summary> void Runner() { while (true) { Task task; // Try find a task to do lock (toDoList) // Lock the task list while grabbing // a task so other threads cant touch it { if (toDoList.Count == 0) return; // nothing left to do so quit this thread task = toDoList[0]; // grab it from the head of the list toDoList.RemoveAt(0); // remove it from the list } // Run the task just grabbed from the list task.Run(); } } }
class Program { static void Main(string[] args) { byte[] data = File.ReadAllBytes("MyYearsData.dat"); ToDoList todo = new ToDoList(); todo.sharedData = data; todo.Go(); } }
Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.
(Comp Sci, Hons - UTS)
Software Developer (Freelancer / Contractor) in Australia.
I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!
Get in touch:
[email protected]
github.com/chrishulbert
linkedin