问题
I wanna build Multi-Threaded procedure for the following code, but not able to correctly build it. I tried using Semaphore to sequentially complete the code but it only executed the myStream2.CopyFrom(myStream1, StrToInt64('$' + SL1[(i - 1)]));
part which comes under else part. The problem presents is that if we restore those streams into output filestream (mystream2) haphazardly, the file will corrupt.
Can anyone help me please.
for i := 1 to SL1.Count do
begin
if Length(SL1[i - 1]) > 12 then
begin
TempDir := SrcDir + 'temp_' +
IntToHex(Random(2147483647) + Random(2147483647), 8) + '\';
ForceDirectories(TempDir);
for k := 1 to 2 do
begin
tempfile := TempDir + IntToHex((i - 1), 8) + '.tmp' + IntToStr(k);
fs := TFileStream.Create(tempfile, fmCreate or fmShareExclusive);
fs.CopyFrom(myStream1, StrToInt64('$' + DecodeRefStr(SL1[(i - 1)])[k]));
fs.Free;
end;
ExecAndWait(SrcDir + 'process.exe', Method + ' ' + '"' + TempDir +
IntToHex((i - 1), 8) + '.tmp1' + '" "' + TempDir +
IntToHex((i - 1), 8) + '.tmp2' + '" "' + TempDir +
IntToHex((i - 1), 8) + '.tmp4' + '"', TempDir,
True, True);
tempfile := TempDir + IntToHex((i - 1), 8) + '.tmp4';
fs := TFileStream.Create(tempfile, fmOpenRead);
myStream2.CopyFrom(fs, 0);
fs.Free;
TDirectory.Delete(TempDir, True);
end
else
myStream2.CopyFrom(myStream1, StrToInt64('$' + SL1[(i - 1)]));
end;
myStream1.Free;
myStream2.Free;
来源:https://stackoverflow.com/questions/37564672/sequential-multi-threading