我想使用需要并行工作的线程来读取文本文件。我知道一些有关如何创建线程和同步(使用互锁和锁定)的信息,但是我无法使用并行线程读取文件。问题是,我需要使用4个线程读取4行,每个线程同时读取不同的行。例如;
线程1 ---第1行;
线程2 ---第2行;
线程3 ---第3行;
线程4 ---第4行;
线程1 ---第5行;
线程2 ---第6行;等等...
文本文件仅包含正整数,即每行具有1个正整数。作业要求我阅读所有内容,对数字进行一些数学运算,并计算所需的总时间。然后,我需要证明并行化所需的时间少于正常的顺序读取(无线程)。
我试图进行一些同步,但我只允许一个线程一次读取一行,而其他3个线程正在等待。结果已经比顺序的要差。
那么,我在做什么错?我需要学习另一章吗?如果是这样,有人可以为此提供材料吗?
这是示例代码;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace Assignment_2
{
class Program
{
private int line_counter = 2;
private string path = "C:\\Users\\Asus\\Desktop\\AdvProgTec1\\ws19\\Assignment_2\\Assignment_2\\TOSUM1.DAT";
private int count = 0; // number of even integers in the list
private double sum = 0; // sum of those even integers
private double temp_number;
private int total_number_of_lines;
public void Process(object state)
{
//string path = "C:\\Users\\Asus\\Desktop\\AdvProgTec1\\ws19\\Assignment_2\\Assignment_2\\TOSUM1.DAT";
//int count = 0; // number of even integers in the list
//double sum = 0; // sum of those even integers
//double temp_number;
//int total_number_of_lines;
try
{
using (StreamReader sr = new StreamReader(path))
{
total_number_of_lines = Convert.ToInt32(sr.ReadLine());
//Console.WriteLine("Total number of numbers here: {0}\n", firstLine);
while (line_counter <= total_number_of_lines)
{
lock (this)
{
temp_number = Convert.ToDouble(sr.ReadLine());
Console.WriteLine("{0} here. Readed line: {1}", Thread.CurrentThread.Name, temp_number);
if (temp_number % 2 == 0) // If the number is even
{
sum += temp_number;
count++;
}
line_counter++;
}
//Interlocked.Increment(ref line_counter);
}
Console.WriteLine("Sum: {0}, Count: {1}", sum, count);
sr.Close();
}
}
catch
{
Console.WriteLine("{0} Aborted!!", Thread.CurrentThread.Name);
}
finally
{
Console.WriteLine("{0} Exiting...", Thread.CurrentThread.Name);
}
}
static void Main(string[] args)
{
Program p1 = new Program();
Stopwatch myWatch = new Stopwatch();
// START THE PARALLEL THREAD METHOD
Thread[] myThreads = { new Thread(p1.Process), new Thread(p1.Process), new Thread(p1.Process), new Thread(p1.Process) };
int thread_counter = 1;
myWatch.Start();
foreach (Thread myThread in myThreads)
{
myThread.IsBackground = true;
myThread.Start();
myThread.Name = "Thread" + thread_counter.ToString();
thread_counter++;
Console.WriteLine("Started thread: {0}", myThread.Name);
//Thread.Sleep(1);
}
foreach (Thread myThread in myThreads)
{
myThread.Join();
}
Console.WriteLine("All my threads are done.");
myWatch.Stop();
Console.WriteLine("Time consumed with Thread method is = {0} msec", myWatch.ElapsedMilliseconds.ToString());
myWatch.Reset();
Console.Read();
}
}
}