Guest User

Untitled

a guest
Feb 18th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.61 KB | None | 0 0
  1. For my USB Disk Ejector program:
  2. --------------------------------
  3.  
  4. I`m catching windows messages related to drive addition/removal. When I get the messages that a drive has been added or removed I rescan all drives and repopulate my list of usb drives.
  5. However sometimes another drive might be added/removed when I'm rescanning all the drives - so I need to scan the drives again.
  6.  
  7. This is perfectly fine, but what I do now is bad - I have a global variable that I increment each time I get the "DrivesHaveChanged" message. I have a thread that rescans the drives but this thread also writes to the global variable too.
  8.  
  9. Help me please:
  10. ---------------
  11. This is essentially a threading problem. I'm writing to a global variable from within my main thread and a child thread - I know this is bad.
  12.  
  13. Any ideas on how I fix this? A critical section is apparently one solution?
  14.  
  15.  
  16. At the moment I do this:
  17. ------------------------
  18. Pseudo-pascal code:
  19.  
  20.  
  21. fChangeMessageCount: global variable - integer
  22.  
  23. procedure CatchTheMessages
  24. begin
  25.  if ItsTheMessageIWant then
  26.  begin
  27.    inc(fChangeMessageCount); //increment it
  28.    if EventsThread.Suspended then EventsThread.Resume;
  29.  end;  
  30. end
  31.  
  32.  
  33. procedure TEventsThread.Execute;
  34. begin
  35.   while not terminated do
  36.   begin
  37.     if self.Terminated then break;
  38.  
  39.     if (fChangeMessageCount > 0) and (fEjector.Busy = false) then
  40.     begin
  41.       sleep(500);  //gives extra time for devices with multi volumes/partitions
  42.       fChangeMessageCount:=0; //set it back to 0 because we're about to scan
  43.       RescanAllDrives;
  44.     end
  45.     else
  46.       self.Suspend;
  47.   end;
  48. end;
Add Comment
Please, Sign In to add comment