I have a question regarding calling methods from different threads. Well I am using WinUSB driver to communicate with USB device. I have separate thread to read data from device. Commands to device are set within main thread. Actually I am using WinUSB_WritePipe and WinUSB_ReadPipe methods to do such operations. In thread where data is read I use asynchronus method of reading with overlapped structure and WaitForMultipleObject. My device has some features that I need to set and this is done via GUI in main thread.
我看到了一些奇怪的行为。 我的问题是,我确实需要锁定这一方法的通话(例如,通话),因为当时只有一对read正在使用或使用这种方法。
OLD WAY:
type TMyThread = TThread
protected
procedure Execute; override;
end;
procedure TMyThread.Execute;
begin
while not Terminated do
begin
WinUsb_ReadPipe(Pipe, Amount, Overlapped)
ErrNo := GetLastError;
if ErrNo = ERROR_IO_PENDING then
begin
wRes = WaitForMultipleObjects(2, @HndEvt, false);
if wRes = WAIT_OBJECT_0 then
begin
ResetEvent(Overlapped.hEvent);
WinUSB_GetOVerlappedResult
DoSomethingWithData; // Do something
end;
end;
end;
end;
MainThread:
begin
// Set device sample rate
WinUSB_WritePipe (Pipe, Amount, Data, ...)
end;
New WAY:
type TMyThread = TThread
protected
procedure Execute; override;
public
procedure Lock;
procedure Unlock;
constructor Create(ASuspended: boolean); override;
destructor Destroy; override;
end;
constructor TMyThread.Create(ASuspended: boolean);
begin
hMtx := CreateMutex(nil, false, nil);
end;
destructor TMyThread.Destroy(ASuspended: boolean);
begin
CloseHandle(hMtx);
end;
procedure TMyThread.Lock;
begin
WaitForSingleObject(hMtx, 10000);
end;
procedure TMyThread.Unlock;
begin
ReleaseMutex(hMtx);
end;
procedure TMyThread.Execute;
begin
while not Terminated do
begin
Lock;
WinUsb_ReadPipe(Pipe, Amount, Overlapped)
Unlock;
ErrNo := GetLastError;
if ErrNo = ERROR_IO_PENDING then
begin
wRes = WaitForMultipleObjects(2, @HndEvt, false);
if wRes = WAIT_OBJECT_0 then
begin
ResetEvent(Overlapped.hEvent);
Lock;
WinUSB_GetOVerlappedResult
Unlock;
DoSomethingWithData; // Do something
end;
end;
end;
end;
MainThread:
begin
// Set device sample rate
Lock; // same mutex as in TMYThread
WinUSB_WritePipe (Pipe, Amount, Data, ...)
Unlock; // same mutex as in TMYThread
end;
这是非常简化的法典,它只是为了描述我的问题,并不反映我的方案拟订技能。 当然,我用同样的ex子,在主线上用同样的方法。
我希望我描述我的问题尽可能简单。 难道我是否需要在不同的路面上锁定这些方法?
感谢你的时间和事先的答复。 确实,我很想这样做!
Br, Nix