Guest User

Untitled

a guest
Feb 18th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.62 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.  
  22. fChangeMessageCount: global variable - integer
  23.  
  24. procedure CatchTheMessages
  25. begin
  26.  if ItsTheMessageIWant then
  27.  begin
  28.    inc(fChangeMessageCount); //increment it
  29.    if EventsThread.Suspended then EventsThread.Resume;
  30.  end;  
  31. end
  32.  
  33.  
  34. procedure TEventsThread.Execute;
  35. begin
  36.   while not terminated do
  37.   begin
  38.     if self.Terminated then break;
  39.  
  40.     if (fChangeMessageCount > 0) and (fEjector.Busy = false) then
  41.     begin
  42.       sleep(500);  //gives extra time for devices with multi volumes/partitions
  43.       fChangeMessageCount:=0; //set it back to 0 because we're about to scan
  44.       RescanAllDrives;
  45.     end
  46.     else
  47.       self.Suspend;
  48.   end;
  49. end;
Add Comment
Please, Sign In to add comment