dcsimg
Results 1 to 31 of 31

Thread: [RESOLVED] Multithreading

  1. #1

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Resolved [RESOLVED] Multithreading

    I'm asking this more out of curiosity than anything else, but I probably would wind up using it if I could trust it.

    For me to truly embrace multithreading, I'd really like it to meet the following criteria:

    • Will run equally well in the IDE as compiled. It would be far less attractive to me if this isn't met.
    • Doesn't require any "separate" dependencies. In other words, it's all done with standard Windows API calls.
    • Shares the same address space as the application that spawned it. I suspect that this would always be the case.

    Also, until I see how it would be implemented, I'm not entirely sure what other features it could have, such as instantiating COM objects, loading forms, etc. Also, it's not clear to me how you'd tell it what functions/procedures to run in the second thread, but I think that would be more clear once the implementation was understood.

    Also, obviously, it would need some kind of standard callback functions for "SuccessfullyCompleted", and "AbnormallyTerminated". Or maybe a "status" variable that's periodically checked by the primary thread would be enough.

    I suppose any limits imposed on the primary thread while the secondary thread is running would have to be well understood.

    Is there anything out there like this?

    Best Regards,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  2. #2
    VB-aholic & Lovin' It LaVolpe's Avatar
    Join Date
    Oct 2007
    Location
    Beside Waldo
    Posts
    17,450

    Re: Multithreading

    Elroy, have you looked in the codebank. I think Krool and Trick both have projects there. Whether or not they meet your criteria, uncertain.
    Insomnia is just a byproduct of, "It can't be done"

    Classics Enthusiast? Here's my 1969 Mustang Mach I Fastback. Her sister '67 Coupe has been adopted

    Newbie? Novice? Bored? Spend a few minutes browsing the FAQ section of the forum.
    Read the HitchHiker's Guide to Getting Help on the Forums.
    Here is the list of TAGs you can use to format your posts
    Here are VB6 Help Files online


    {Alpha Image Control} {Memory Leak FAQ} {Unicode Open/Save Dialog} {Resource Image Viewer/Extractor}
    {VB and DPI Tutorial} {Manifest Creator} {UserControl Button Template} {stdPicture Render Usage}

  3. #3

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    Hi LaVolpe,

    Yeah, I've studies both of their projects, although I've never gotten to the point where I started testing things. Trick's stuff is always fascinating, but what he posted looked rather involved. And I'm very impressed with Krool's work as well, but his approach is also rather involved.

    I wouldn't mind involved code. However, as stated above, before I'd probably make extensive use of it, it'd probably need to meet my criteria. And, if I understand them correctly, neither Trick's nor Krool's approach does.

    It just might not be possible. There is a "MaxNumberOfThreads=1" setting in the .VBP file, but I'll readily admit that I don't know what would happen if I started tampering with that. There's also a "ThreadPerObject=0" setting.

    Best Regards,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  4. #4
    PowerPoster
    Join Date
    Jun 2013
    Posts
    3,804

    Re: Multithreading

    Quote Originally Posted by Elroy View Post
    For me to truly embrace multithreading, I'd really like it to meet the following criteria:

    • Will run equally well in the IDE as compiled. It would be far less attractive to me if this isn't met.
    • Doesn't require any "separate" dependencies. In other words, it's all done with standard Windows API calls.
    This is not possible with VB6.
    If you want to test stable (threaded) behaviour in the IDE, then you will always need:
    - a precompiled, external binary (usually an *.exe or a *.dll).


    Quote Originally Posted by Elroy View Post
    • Shares the same address space as the application that spawned it. I suspect that this would always be the case.
    I guess what you really mean is, that both (the WorkerThread as well as the Main-Thread)
    have access to a "shared memory-area".

    One can create such a thing even among two Processes (then use SaveArray-Bindings in both Processes,
    or threads) to make that shared memory-area conveniently accessible via VB-Code).

    That's the easiest, most convenient, most robust and also best performing solution I can think of.

    So my recommendation to you as a "beginner with parallelism" is, to leave out all the "COM-STA-stuff",
    and start implementing such a "Shared-Mem-Solution" between two Processes:
    1) running your IDE (as the Main-Process/Thread), which later spawns (and also terminates) a secondary Process -
    2) as a shelled little VB6-compiled Std-Exe, which only has code in Sub Main (and no Forms)

    If you encapsulate the Shared-Memory-Area (including the SafeArray-Bindings) in a small Private-Class,
    (which later on is sitting as a shared code-module in both VB-Projects), the communication and
    Data-Processing/Sharing becomes a breeze.



    Olaf

  5. #5
    PowerPoster
    Join Date
    Feb 2006
    Posts
    19,164

    Re: Multithreading

    This is so hazardous that VB6 made a big change from VB5 to support Thread Local Storage.

    Without that things were too chaotic. Few VB programmers were going to be capable of dealing with synchronized access to data. To even offer that would mean implementing a lot of new language features that would be incompatible with many existing features.

    In the few cases where you can't afford to have the user interface thread tied up with long-running synchronous code there are only a few safe options:

    • ActiveX EXE.
    • Separate process you communicate with some other way.
    • A library that creates additional Apartments and provides some sort of data marshaling mechanism.

  6. #6

  7. #7
    Frenzied Member
    Join Date
    Jun 2012
    Posts
    1,076

    Re: Multithreading

    Quote Originally Posted by Elroy View Post
    Will run equally well in the IDE as compiled. It would be far less attractive to me if this isn't met.
    My approach (VBMThread) can run in the IDE, though you will never get debugging to work. (breakpoints etc.)
    That's why there is a special DebugMode property in the Thread class that indicates if the background worker will run in the same thread as the main one. You can set for example .DebugMode = InIDE().

    Quote Originally Posted by Elroy View Post
    Doesn't require any "separate" dependencies. In other words, it's all done with standard Windows API calls.
    As Schmidt already said this is certainly not possible. At least to "trust" on.

    Quote Originally Posted by Elroy View Post
    I'm not entirely sure what other features it could have, such as instantiating COM objects, loading forms, etc. Also, it's not clear to me how you'd tell it what functions/procedures to run in the second thread, but I think that would be more clear once the implementation was understood.
    In the backgroundworker you can access the project variables from the main thread. Also you can create new COM objects within the background worker (also early-bound from main project references), e.g. ADODB. In the demo of VBMThread is also a modeless form loaded. So IMO it's quite flexible as it would be in the main thread with just some rare pitfalls and exception. E.g. accessing the App object (e.g. App.Path) does not work within the background worker.

    Quote Originally Posted by Elroy View Post
    Also, obviously, it would need some kind of standard callback functions for "SuccessfullyCompleted", and "AbnormallyTerminated". Or maybe a "status" variable that's periodically checked by the primary thread would be enough.
    In VBMThread you have a Complete event which is called after the Thread has ended. (hThread = 0)
    The Data object in that Complete event can advise if the background worker has ended successfully or was shutdown via the Canceled property.
    However, the Canceled property is only meaningful if you set it in the background worker. In the demo you can certainly see how it's done.

  8. #8

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    To Krool & Trick,

    Thank you both for summarizing your multithreading approaches. I am extremely impressed with the work that both of you have done.

    To others interested, here's the link to Krool's approach.

    I'm starting to lean toward the idea that multithreading in the IDE probably isn't a good idea, especially since we'd lose any debugging capabilities. Without debugging, why not just compile to test? (rhetorical) Also, the way Trick has things set up, you can still execute in the IDE, just not in a multithreaded way.

    I found Trick's demo project where he uses multithreading. In his DirectX9 CodeBank entry, it's the SharedResources demo.

    I've also re-packaged it so that it's all in one folder (see attached). Trick, I hope you don't mind this. Also, the .IDL files are there for both of the TypeLibs being used in that project (one for the DX9 stuff and the other for API calls for the multithreading). For anyone downloading this and attempting to run it, you'll probably need to re-reference both the dx9vb.tlb and EXEInitialize.tlb in the project. If you intend to continue using these TypeLibs for development, you'd probably want to move them to your System32 (or SysWOW64 for 64-bit) and register them there. And, as Trick states, once compiled, you'll no longer have any need for these TypeLibs.

    Later on, I'll probably strip out the DX9 stuff and make a demonstration for just the multithreading. I'm impressed with the way he's locking portions of memory so that the two threads don't have collisions. I'll be sure to leave that in the cut-down demonstration.

    I'm wondering if we could actually wind up in separate CPU cores when we do this. I suspect we could. However, it's almost certain that it's up to Windows to figure all that out, and not something that we'd even want to control.
    Attached Files Attached Files
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  9. #9

  10. #10

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    Okay, I've cut Trick's multi-threading approach down to the bare minimum, and it seems to work.

    Again, it only works if compiled. However, I've set this demo up such that it'll still run in the IDE, just as a single-threaded program.

    As far as I can tell, there doesn't seem to be a problem with just sharing whatever memory we want. In this demo, I'm sharing the gbEndFlag variable's memory, and I'm also sharing the frmMain (or specifically whatever memory it takes to change the frmMain.Text1.Text property).

    One caveat I did run into was the following: We should be careful to make sure whatever variables and objects are referenced in the second thread, are created and ready-to-go from the main thread. Things can go south quickly if we attempt to access objects in the second thread that are destroyed in the main thread. But this sort of makes sense. Instantiating COM objects in the second thread doesn't seem to work either (but I'm not sure that'd be needed).

    In Trick's full example, he showed how to lock and unlock memory segments, which is certainly useful in certain circumstances. However, from this simple test, it doesn't seem to be absolutely essential.

    Also, he had logic in the demo for pulsing events to signal things to the second thread. However, that doesn't seem to be absolutely essential either. But, I suppose if we want to pause the second thread, and have it wait for instructions, then this would be essential.

    Comments and critiques of this are absolutely encouraged, as I'd certainly like to know any flaws in this demo.

    And specifically, I've reworked the modMultiThreading.bas module, but I still don't have every aspect of it in my head. Any additional comments/annotations/explanations on that module are more than welcome.

    Ahhh, and Trick's EXEInitialize.tlb (along with the .IDL) are still needed. They're both in the attached ZIP file.

    @baka: If you're listening, this would seem to be a pretty good solution to this thread. Whatever process you have that's taking a long time, just run it in a second thread, and then you can still drag your form around with no delay in that second thread's processing. You can see that on this example. In the IDE, it pauses. However, when compiled, the loop keeps running when you drag the form around by the title-bar.

    Best Regards,
    Elroy
    Attached Files Attached Files
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  11. #11
    Addicted Member
    Join Date
    Feb 2017
    Posts
    253

    Re: Multithreading

    Elroy:
    Would not creating an ActiveX and then sending (marshaling the results)
    between the Main App and the ActiveX give the same result?
    For example I have a client based server which receives continuous data from a third party. That data is then massaged and then forwarded (set cross process) on to the client app for final processing.

    Also are Not the menus one places in a VB Form in a separate ActiveX or does VB implement a separate thread for them -- ??? -- as one can access VB's menu system without interrupting other controls such as when painting a picturebox.

  12. #12

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    Hi vb6forever,

    If you mean an ActiveX EXE, then yes, I think you'd accomplish the same thing. However, I just like the approach of keeping everything wrapped into one project for certain things (even with limitations).

    Also, regarding VB6 menus, they're definitely in the same thread. If you'd like to prove that to yourself, just add a menu to the above multithreading demo, and then watch it pause when you access the menu while running in the IDE. I didn't test it, but I'm certain the same thing would happen when compiled if that second thread wasn't invoked.

    Best Regards,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  13. #13

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    Hmmm, actually loading forms and instantiating COM objects in a second thread seems to work just fine. It just seems that the second thread has to be very careful to clean up after itself (and personally, I think that's a good thing).

    So, it can use variables and objects created/instantiated in the first thread. And it can also instantiate its own objects. It's just not good to instantiate objects in one thread and un-instantiate them in the other (which again means that the second thread needs to be sure and clean up after itself).

    Attached is a project where the second thread loads and uses a second form. (When compiled) you can tell the second form is managed by the second thread, as the counting stops when you drag it, but the counting does not stop when you drag the first form.

    Enjoy,
    Elroy
    Attached Files Attached Files
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  14. #14

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    @Trick,

    I think I found a bug in your CreateAsm procedure:

    Name:  Asm.jpg
Views: 254
Size:  35.9 KB

    It seems you're requesting 15 bytes of memory, but that second circled section is assigning the 16th, 17th, 18th, & 19th bytes from the beginning. Maybe the paging rounding up is protecting you. I'm not sure.

    Here's your version of the code:

    Code:
    
    ' // Create binary code.
    Private Function CreateAsm() As Long
        Dim hMod    As Long
        Dim lpProc  As Long
        Dim ptr     As Long
    
        hMod = EXEInitialize.GetModuleHandle(ByVal StrPtr("kernel32"))
        lpProc = EXEInitialize.GetProcAddress(hMod, "TlsGetValue")
    
        If lpProc = 0 Then Exit Function
    
        ptr = EXEInitialize.VirtualAlloc(ByVal 0&, &HF, MEM_RESERVE Or MEM_COMMIT, PAGE_EXECUTE_READWRITE)
    
        If ptr = 0 Then Exit Function
    
        ' push  tlsIndex
        ' call  TLSGetValue
        ' pop   ecx
        ' push  DWORD [eax]
        ' push  ecx
        ' jmp   DWORD [eax + 4]
    
        EXEInitialize.GetMem4 &H68, ByVal ptr + &H0:            EXEInitialize.GetMem4 &HE800, ByVal ptr + &H4
        EXEInitialize.GetMem4 &HFF590000, ByVal ptr + &H8:      EXEInitialize.GetMem4 &H60FF5130, ByVal ptr + &HC
        EXEInitialize.GetMem4 &H4, ByVal ptr + &H10:            EXEInitialize.GetMem4 tlsIndex, ByVal ptr + 1
        EXEInitialize.GetMem4 lpProc - ptr - 10, ByVal ptr + 6
    
        CreateAsm = ptr
    
    End Function
    
    
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  15. #15
    Addicted Member
    Join Date
    Jun 2015
    Posts
    243

    Re: Multithreading

    One approach I have used was to do any extra threads from a C dll, then you can notify the main UI of progress or events through SendMessage/PostMessage and a subclass on your main window to catch the messages. Its simple and stable enough to use for a vb based x86 debugger. Also works cross process you can even implement a synchronous scripting client that works across processes.

  16. #16
    PowerPoster
    Join Date
    Jun 2015
    Posts
    2,069

    Re: Multithreading

    I definitely recommend Curland / Krool's method of multithreading.
    It's straight forward and by the book (obeying COM threading rules) so to speak, and it piggy backs on the VB6 runtimes threading support already built into DLLs. Plus you can rely on the COM subsystem for automatic marshalling of IDispatch Objects (anything latebound), Strings, Arrays and Variants, for passing data between threads.

    edit: also thanks to the Trick, Krool's DLL can be used SxS.
    Last edited by DEXWERX; May 29th, 2018 at 06:42 AM.

  17. #17
    Hyperactive Member
    Join Date
    Aug 2016
    Posts
    280

    Re: Multithreading

    Multiprocess vs multithreading,Are multiple processes more stable?!

  18. #18
    Frenzied Member
    Join Date
    Jun 2012
    Posts
    1,076

    Re: Multithreading

    Quote Originally Posted by xxdoc123 View Post
    Multiprocess vs multithreading,Are multiple processes more stable?!
    https://blogs.datalogics.com/2013/09...rallelization/

  19. #19

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    Alright, no hijacking my thread.

    @Dex: Yeah, I've got no doubt that Krool put together a very nice way to do multithreading. And, down the road, I'll almost certainly take a look at it. However, for now, I'm going to stick with Trick's approach. When following a set of rules, it seems to work quite well. I'm still sorting out several things though.

    For one, it's unclear to me whether we actually need the TypeLib or not.

    @Trick, if you happen to see this, would you please weigh in on that? In other words, can we just make all the API declarations in the VB6 code? In one of your multithreading posts, you talk about ...

    removing the check __vbaSetSystemError
    ... so I'm not sure it's possible to just eliminate the TypeLib.
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  20. #20
    Frenzied Member
    Join Date
    Feb 2015
    Posts
    1,140

    Re: Multithreading

    I think I found a bug in your CreateAsm procedure:
    No, it always round up to the page boundary (4096).

    I definitely recommend Curland / Krool's method of multithreading.
    It's straight forward and by the book (obeying COM threading rules) so to speak, and it piggy backs on the VB6 runtimes threading support already built into DLLs. Plus you can rely on the COM subsystem for automatic marshalling of IDispatch Objects (anything latebound), Strings, Arrays and Variants, for passing data between threads.
    My method is more low-level. For example, if you need to marshal the data you should do it yourself (CoGetInterfaceAndReleaseStream). My method is like C++ _beginthread.

    @Trick, if you happen to see this, would you please weigh in on that? In other words, can we just make all the API declarations in the VB6 code?
    I think we can avoid the tlb, i was writing about it:
    Combining your method with mine it is possible to create a nice multithreading without TLB i think. It is also needed to do releasing of IExprSrv object in order to release its memory.
    In one of your multithreading posts, you talk about ...
    I think it's possible but it violates the behavior of the other threads (for example if it's calling that function or checks Err.LastDllError). I did like this in the DLL multithreading (like Krool) to avoid using tlb.

  21. #21

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: Multithreading

    Okay, I've learned that (to use Trick's approach) we must have the TypeLib.

    Something as simple as ...

    Code:
    
    Private Declare Function GetProcessHeap Lib "kernel32" () As Long
    
    ... declared in the project will crash everything. However, if it's in the TypeLib, all works fine. Apparently, you just can't call locally declared API calls from a second thread. That seems to be the common denominator to what makes it crash. Therefore, TypeLib is absolutely essential (during IDE development and compiling, but not needed for distribution).

    I've reworked and renamed Trick's TypeLib (and recompiled it) so that it has precisely what the modMultiThreading.bas module needs. The TLB and IDL are included. A complete demo is attached.

    Also, I've included an ability to "pause" and "resume" the second thread.

    Remember, you must compile before you'll actually be using a second thread. To see it in action, compile and then drag around the form, noticing that the TextBox keeps showing random numbers while the form is being drug around (i.e., while the non-client area has control of the main thread).

    I think I'm going to be done with this project for a while. A HUGE thanks to The Trick for showing how to do all of this!

    Don't forget that you'll need to re-reference (and possibly register) the MultiThread.tlb for things to work in the VB6 IDE. Also, if you registered the other EXEInitialize.tlb, you may need to un-register that one first, as I didn't change the UUIDs. I've included some VB-Script typelib register/unregister files as well. I believe it was Dilettante who put those together but I don't remember for sure as I've had them for quite some time.

    I might work on it more in the future, but I'll start a new thread for that. It would be nice if we could spawn as many new Windows threads as we like, rather than be limited to one additional thread.

    Best Regards,
    Elroy

    EDIT1: And just to say it, I've worked hard to shove all the complex stuff down into the modMultiThreading.bas module, including all checks for doing things in the wrong order. You'll notice that the code in the frmMain checks very little, and you can bounce on the buttons all you want with no ill effect. I'd just like this to be as easy to use as it possibly can be.
    Attached Files Attached Files
    Last edited by Elroy; May 30th, 2018 at 12:42 PM.
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  22. #22

  23. #23
    PowerPoster
    Join Date
    Jun 2013
    Posts
    3,804

    Re: Multithreading

    Quote Originally Posted by xxdoc123 View Post
    Multiprocess vs multithreading,Are multiple processes more stable?!
    Of course they are - you might want to play around with an appropriate Demo I've just placed in the CodeBank:
    http://www.vbforums.com/showthread.p...-SharedMemory)

    Olaf

  24. #24
    Addicted Member
    Join Date
    Feb 2017
    Posts
    253

    Re: [RESOLVED] Multithreading

    One area which seems not to work -- whether using multiple threads, ActiveX.EXE or SharedMemory -- seems to be when trying to have the user interact at the same time other action is occurring within a control. For example:
    A picturebox drawing routine where the user wants to interact with that drawing using tools.
    One could move most functions for either the graphic drawing or tool usage and/or both actions (drawing and user), into different threads, ActiveX.exe or SharedMemory, but since they both interact with the same picturebox, they both need the Picturebox paint event. So some priority needs to be established so the two actions can mesh while using Paint. So does one gain any advantage
    by moving the routine(s) out of the original process?
    Last edited by vb6forever; May 30th, 2018 at 09:52 PM.

  25. #25

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: [RESOLVED] Multithreading

    Quote Originally Posted by vb6forever View Post
    One area which seems not to work -- whether using multiple threads, ActiveX.EXE or SharedMemory -- seems to be when trying to have the user interact at the same time other action is occurring within a control. For example:
    A picturebox drawing routine where the user wants to interact with that drawing using tools.
    One could move most functions for either the graphic drawing or tool usage and/or both actions (drawing and user), into different threads, ActiveX.exe or SharedMemory, but since they both interact with the same picturebox, they both need the Picturebox paint event. So some priority needs to be established so the two actions can mesh while using Paint. So does one gain any advantage
    by moving the routine(s) out of the original process?
    Hi vb6forever,

    If you look at the "SharedResources" example in the demos provided by The Trick over in his thread about DirectX9, you'll find an example of how he deals with that problem (at least in a way). He locks shared memory when the second thread is using it, and re-tries for a period of time when the locking won't work. If I remember correctly, the re-trying is done in both the primary and secondary thread. In that way, one thread gets a chance to get to a "completion" point before the other thread starts meddling with it. I'm not sure how you'd go about doing that with a PictureBox, but you could use some of the CreateEvent, ResetEvent, PulseEvent, WaitForSingleObject functions to do it.

    Also, you've got to be careful when sharing objects (such as a PictureBox) across threads. Strictly speaking, the "contract" with a COM object is that only the thread that created it shall use its methods. I've played around with breaking that contract, but I'm not sure how far it can be pushed. However, when CreateThread is used, a thread is created "within the virtual address space of the calling process" (per Microsoft).

    Good Luck,
    Elroy
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

  26. #26
    PowerPoster
    Join Date
    Jun 2015
    Posts
    2,069

    Re: [RESOLVED] Multithreading

    Quote Originally Posted by Elroy View Post
    Also, you've got to be careful when sharing objects (such as a PictureBox) across threads. Strictly speaking, the "contract" with a COM object is that only the thread that created it shall use its methods.
    you're not completely wrong, but to clarify that's not a COM Contract. STA objects can only be instantiated within an STA, and can only be accessed from the STA they are instantiated from. Every other thread needs to use a proxy for access. That's why I recommended Curland/Krools method, because you can let the COM subsystem do the interface marshalling auto magically. Otherwise you gotta do it yourself using CoGetInterfaceAndReleaseStream as Trick pointed out.

    you should try that approach out, and manually Marshal your interface to the objects you are trying to access from another thread.

  27. #27
    Member
    Join Date
    Jun 2013
    Posts
    43

    Re: [RESOLVED] Multithreading

    And you have to be super careful to use critical sections to protect any global data. Interlocked instructions are also very useful for shared counters. Otherwise you end up with heap corruption or non nonsensical shared counters that might not show up for hours/days/weeks depending on what your app does. I also use winapi to turn on terminate on heap corruption in anything I do that is multi threaded. In that way I at least get a crash I hopefully reproduce and take a look at in windbg.

    I have also found that certain objects like scripting.dictionary require protection or weird things can happen days later.

  28. #28
    Fanatic Member wqweto's Avatar
    Join Date
    May 2011
    Posts
    761

    Re: [RESOLVED] Multithreading

    Quote Originally Posted by vbcommander View Post
    I have also found that certain objects like scripting.dictionary require protection or weird things can happen days later.
    Scripting.Dictionary is marked ThreadingModel=Apartment in registry. You cannot legitimately execute any of its methods on any other thread besides the thread that is servicing the STA its instance was created on.

    Even if you try to sync your threads with critical sections (i.e. impl blocking from client-side i.e. from "outside") you cannot guarantee that the class in question is not using an hwnd for instance and GUI in Windows is single threaded by nature.

    When using threading in VB6 there is no single case for critical section usage as VB6 cannot implement free threaded classes and then using instances of free threaded classes is automagically synchronized by COM apartment proxies (i.e. no manual sync needed).

    cheers,
    </wqw>

  29. #29
    PowerPoster
    Join Date
    Jun 2015
    Posts
    2,069

    Re: [RESOLVED] Multithreading

    You can however proxy the interface from one STA to another, if you need to access it from another thread.
    If you use Krool's threading DLL, COM will do it automagically if you pass it back as IDispatch (Object) in the thread callback's Variant parameter.

  30. #30

  31. #31

    Thread Starter
    PowerPoster Elroy's Avatar
    Join Date
    Jun 2014
    Location
    Near Nashville TN
    Posts
    4,622

    Re: [RESOLVED] Multithreading

    @The Trick: I saw. I'm on a consulting gig right now, but I'm excited to get back home and play with it. It looks really exciting.
    Any software I post in these forums written by me is provided “AS IS” without warranty of any kind, expressed or implied, and permission is hereby granted, free of charge and without restriction, to any person obtaining a copy. Please understand that I’ve been programming since the mid-1970s and still have some of that code. My contemporary VB6 project is approaching 1,000 modules. In addition, I have a “VB6 random code folder” that is overflowing. I’ve been at this long enough to truly not know with absolute certainty from whence every single line of my code has come, with much of it coming from programmers under my employ who signed intellectual property transfers. I have not deliberately attempted to remove any licenses and/or attributions from any software. If someone finds that I have inadvertently done so, I sincerely apologize, and, upon notice and reasonable proof, will re-attach those licenses and/or attributions. To all, peace and happiness.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width