|
Multithreading with multi-instancing and inter-thread communication support
|
Email
|
| Submitted on: |
7/3/2001 3:29:55 AM |
| By: |
Srideep Prasad
|
| Level: |
Advanced |
| User Rating: |
By 190 Users |
| Compatibility: |
VB 5.0, VB 6.0 |
| Views: |
124348 |
|
(About the author) |
|
|
|
This article teaches how to multithread safely and effectively using pure VB. No need to use C/C++ or the infamous CreateThread API notorious for its instability with VB 6. Simple and effective code complete with a HTML article documenting the various aspects of Multithreading are included to help you get started right away ! What's more, multiple-app instances are also now supported ! So say goodbye to Timers, crashes, threading API's and "freezing" forms. And if you find this code useful, remember that your vote will be GREATLY APPRECIATED ! (NOTE: When you create your own multithreaded app, set the threading model to "Thread per object")
NO EXPERIENCE OF C/C++ IS REQUIRED . SO NO NEED TO GO RUNNING ABOUT FOR A VC++ COMPILER. ENTIRELY BASED ON MICROSOFT'S ACTIVEX TECHNOLOGY FAMOUS FOR ITS SCALABILITY AND STABILITY. AND FOR THE SCEPTICS, THIS DEMO CAN CREATE 102 THREADS FOR A MEAGRE RAM MEMORY REQUIREMENT OF 2.5MB ALTOGETHER (A STANDARD BLANK FORM EXE TAKES AROUNG 2.0 MB OF MEMORY IN WIN98 FE)
IF YOU FIND THIS ARTICLE USEFUL PLEASE VOTE FOR ME !
[REQUIRES VB 5(Sp2) / VB 6)
This article has accompanying files
|
 |
| |
Terms of Agreement:
By using this article, you agree to the following terms...
- You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
- You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
- You may link to this article from another website, but ONLY if it is not wrapped in a frame.
- You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
|
Multithreading
Multithreading - Understanding the pros and cons
One of the greatest problems of the earlier Win16 environment was that an application could do only one thing at one time (that is "single thread"). However with the advent of Windows NT 3.5x, this changed. In 1995, with the release of Windows 95 this ultra powerful technique came to be used in the common PC.
So what is the use of Multithreading ? - Consider Microsoft Word 97 or higher. It checks spelling while you type ! It does it by multithreading - i.e running two "threads" (in layman's language a "thread" is nothing but a piece of code, a sub or function running simultaneously with the main program). In VB 5, a new function AddressOf was introduced that enabled VB programmers to get the address of any public function in a standard module. This enabled developers to use the CreateThread API to create raw Win32 threads. Though this was effective in VB 5.0, with VB 6.0 it crashes miserably !
Even at planet-source-code.com, I came across a multithreading demo using the CreateThread API. Though THE PROGRAM works with VB 6, it is VERY unstable. Also For ... Next loops, Msgbox..., Open .. etc statements do NOT work in the multithreaded procedures!
Does this mean we cannot multithread safely !? Does it mean that we have to worry about
"exception errors" and GPF's popping up any time ?
The Answer is a BIG NO !
Multithreading is VERY easy once you master the concepts... So just have a look at the sample code.. You will understand just how easy it is to perform true and safe multithreading in VB !
If you gained any information, or if this article is useful to you, a vote of yours will be appreciated. If you found it useless.... just DELETE it !
Multithreading In VB 6 - The Safe Way
The trick to effective and safe multithreading in VB is to use the ActiveX EXE project type (set to standalone EXE). The trick here is to create a new object on a new thread by callin the CreateObject() function and to create the Form that you want to be multithreaded from within this object. As a reult the form is created on a new thread, both of them can run almost independently of the other ! The only problem is managing the code re-enterancy - VB calls the Sub main() procedure every time a new object is created - we must find whether the main window is shown or not - if not we must initialize it. This method is actually very easy ! Just check out the sample code and I am sure that you will be Multithreading right
away
What's more - this code now even demonstrates how to communicate between
threads !
And if you found this code useful - be sure to vote for me ! After all, coding is a tough job, and so is writing a tutorial
!
IMPORTANT: You can now download a new generic multithreader component at
the following link http://planet-source-code.com/vb/default.asp?lngCId=26900&lngWId=1
. This component allows you to multithread any sub or function in a standard
EXE. No ActiveX EXEs needed (PS:Thanks for all your votes And I am happy to know
that my articles are of some use to you !)
|
|
Download article
Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. Afterdownloading it, you will need a program like Winzip to decompress it.Virus note:All files are scanned once-a-day by Planet Source Code for viruses, but new viruses come
out every day, so no prevention program can catch 100% of them. For your own safety, please:
- Re-scan downloaded files using your personal virus checker before using it.
- NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.
- Scan the source code with Minnow's Project Scanner
If you don't have a virus scanner, you can get one at many places on the net
including:McAfee.com
|
Terms of Agreement:
By using this article, you agree to the following terms...
- You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
- You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
- You may link to this article from another website, but ONLY if it is not wrapped in a frame.
- You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
|
Other 8 submission(s) by this author
|
|
Report Bad Submission
|
Your Vote
|
| |
Other User Comments
|
7/8/2001 11:37:44 AM: Srideep Prasad
IMPORTANT MESSAGE FROM AUTHOR:PLEASE RUN THE DEMO AS A COMPILED EXE ONLY !!! ALSO MAKE SURE YOU HAVE VB 5(SP2) / VB 6 ONLY ! (If this comment was disrespectful, please report it.)
|
7/16/2001 3:17:15 AM: Edwin Vermeer
You probably would like to communicate between the instances of youre executable. I did something like this in an app of mine. The code pasted below is a rip from this project, so it probably need some rewriting. If you want to do this, then create a form with the name parser. The code in the main module is also a litle different. Here it comes: '----------------------------------- ' Put this code in the beginning of your app. '----------------------------------- Dim bSubApp as Boolean If App.PrevInstance = True Then ' Send message to master app dim txtPrevHandle as String dim lngPrevHandle as String bSubApp = True load Parser DoEvents txtPrevHandle = GetSetting(App.Title, "ActiveWindow", "Handle") lngPrevHandle = CLng(Val(txtPrevHandle)) Doevents SendMessage lngPrevHandle, WM_SETTEXT, 0, ByVal CStr("SubApp ") & Str(Parser!CommandParser.hwnd) DoEvents Else ' Open parser form bSubApp = False load Parser DoEvents End If
(If this comment was disrespectful, please report it.)
|
7/16/2001 3:17:48 AM: Edwin Vermeer
'------------------------------------- ' Put the code below in the parser form '------------------------------------ Dim lngSubApp() as Long Private Sub Form_Load() If not bSubApp SaveSetting App.Title, "ActiveWindow", "Handle", Str(CommandParser.hwnd) Redim lngSubApp(0) as Long End If End Sub
Private Sub CommandParser_Change() Dim txtCommand as String Dim txtSubCommand as String txtCommand = left(CommandParser, instr(1, CommandParser & " ", " ") - 1) txtSubCommand = trim(Mid(CommandParser, instr(1, CommandParser & " ", " "))) Select Case txtCommand Case "SubApp" ' Keep track of all the sub applications Redim Preserve lngSubApp(Ubound(lngSubApp)+1) As Long lngSubApp(Ubound(lngSubApp)) = CLng(Val(txtSubCommand)) Case "Quit" End End Select CommandParser = "" End Sub
(If this comment was disrespectful, please report it.)
|
7/16/2001 3:19:46 AM: Edwin Vermeer
Sorry for the layout. :( (If this comment was disrespectful, please report it.)
|
7/16/2001 5:02:06 AM: Srideep Prasad
Thanks Edwin ! Anyway, I already know of a method to communicate between instances. You can use Mailslots for this, and I have also achieved inter-thread communication. (If this comment was disrespectful, please report it.)
|
8/14/2001 7:19:00 AM: Neil Giddings
Hold on here m8, I just tested this out as I too am really struggling with threads and thought this may work. This isn't multi-threading properly, if I put a do loop in the main form to display the time in the caption with a doevents in the code to allow me to click button etc and as part of the form load in the other form, which should be multitasked, I put a msgbox and run the code this is what I get.
The timer ticks away and updates as I would expect it too but then I hit the button to create a new form the msgbox is displayed and halts the time being updated. So it isn't multi tasking at all.
Can you help me out, as to what's wrong?
(If this comment was disrespectful, please report it.)
|
8/14/2001 12:49:56 PM: Srideep Prasad
Neil - The problem you have mentioned has a simple solution - Check out your e-mail since I have e-mail the solution to you (If this comment was disrespectful, please report it.)
|
8/25/2001 4:21:52 AM: Kristi
Good work,got 5 :) (If this comment was disrespectful, please report it.)
|
8/29/2001 6:07:35 PM: JimM
Srideep: How can I get one thread to terminate another? (If this comment was disrespectful, please report it.)
|
8/30/2001 1:12:36 PM: Srideep Prasad
Jimm, I have e-mail a solution to your problem.. Please check your mailbox
(If this comment was disrespectful, please report it.)
|
9/6/2001 5:45:17 PM: Tomfoolry
Why not post the answers to the questions here instead of emailing them. (If this comment was disrespectful, please report it.)
|
9/6/2001 11:06:18 PM: Nazer Mohamed
Got 5! Please proceed with posting answers and try not to send the mail. (If this comment was disrespectful, please report it.)
|
9/7/2001 7:12:18 AM: Hawkeye
Excellent article!! Very timely, I might add, as I have employed the techniques in a large database program I am creating for my client. BTW, could you send a copy of the answers you have emailed to the other commenters, as I have similar problems.
Thank you and, please keep bringing this information to our attention. (If this comment was disrespectful, please report it.)
|
9/7/2001 1:03:43 PM: Srideep Prasad
THANKS FOR ALL YOUR VOTES ! But I would like to let all of you know that I have developed a generic multithreader that you can use to implement multithreading in any Standard EXE. You could check out the code at - http://planet-source-code.com/vb/default.asp?lngCId=26900&lngWId=1 (If this comment was disrespectful, please report it.)
|
9/17/2001 6:30:11 AM: Bard
Is the most up-to-date code available to download from Planet-Source-Code.com? (If this comment was disrespectful, please report it.)
|
9/24/2001 9:48:23 PM: Yannick
Srideep: I would also like to know how to get one thread to terminate another? (If this comment was disrespectful, please report it.)
|
9/24/2001 9:49:38 PM: Yannick
Srideep: I would also like to know how to get one thread to terminate another? (If this comment was disrespectful, please report it.)
|
11/7/2001 11:26:49 AM: Donald Derrick
This is excellent code. It has helped me get an assignment that aught to have been given to the C++ coders done. Now all I need is a timer w/ callbacks and w/o the need to a hwnd! (If this comment was disrespectful, please report it.)
|
11/11/2001 3:29:07 AM: sherwin
this+works+great%2E++but+it+doesnt+work+dlls+being+called+by+ASP+and+registered+under+CO M+%2FMTS%2C+please+help%2E (If this comment was disrespectful, please report it.)
|
7/17/2002 1:58:45 PM: Luis Cantero
Thanks a lot for this tutorial, I had some issues with it and I posted the solutions I've found for everyone to profit: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=36997&lng WId=1 (If this comment was disrespectful, please report it.)
|
7/17/2002 3:51:25 PM: Dusp2000
Well, how do you send data from the mainform to the different threads and from thread to thread ???
Tnx (If this comment was disrespectful, please report it.)
|
9/20/2002 10:08:32 AM: TV2k.net
I DID IT! I created a working, kinda fast small HTTP server with this! =)
(If this comment was disrespectful, please report it.)
|
9/28/2002 9:33:40 AM:
Good Work Srideep, but I have some difficulties here.
When I use this example with Winsock control, either bind nor listen with UDP / TCP protocol, I got an error msg. telling that the 'Addresses is in use', How can I solve this problem.
Anyway 5 globe from me...
(If this comment was disrespectful, please report it.)
|
3/5/2003 9:13:04 PM:
Wondering if it is possible to have two different apps and use two threads to communicate with each other. (If this comment was disrespectful, please report it.)
|
5/28/2003 9:28:38 PM:
This is a good article, and uses much safer logic that most others I have read, but it uses a separate process (an ActiveX EXE) to accomplish Multithreading. There are many drawback to this approach (most notably performance) - all else aside Bravo !!
However, if your interested in creating robust multithreaded VB6 applications, Components or OCX controls then see the Thread Factory product at http://www.halfx.com (If this comment was disrespectful, please report it.)
|
11/1/2003 11:12:02 PM: DanDaMan
'Good Work Srideep, but I have some difficulties here. When I use this example with Winsock control, either bind nor listen with UDP / TCP protocol, I got an error msg. telling that the 'Addresses is in use', How can I solve this problem. Anyway 5 globe from me... '
set the winsock's localport to 0, took me forever to find this when programming
nice work! (If this comment was disrespectful, please report it.)
|
3/5/2004 1:51:50 PM:
An excellent example, btw how can I destory one of the thread? Could you send me some hint? my email is zteff_wong@hotmail.com (If this comment was disrespectful, please report it.)
|
4/4/2004 6:02:56 PM: Bill D
GREAT EXAMPLE!!! refered via: http://www.experts-exchange.com/Programming/Programming_Languages/Visual_Basic/Q_2094291 5.html (If this comment was disrespectful, please report it.)
|
10/22/2004 12:52:37 AM:
Hi, One thing I'm not getting to work is to close all windows opened by the main form when it is close.
Any help would be great.
Paul (If this comment was disrespectful, please report it.)
|
11/3/2004 2:05:35 PM:
Really great article, Srideep. I was struggling with VB multithreading and this came along like a dream. Thanks a bunch ! (If this comment was disrespectful, please report it.)
|
1/20/2005 3:55:25 AM:
Bad!I want to make one routine in a new thread,The active exe is very awful!help!!! (If this comment was disrespectful, please report it.)
|
1/20/2005 4:38:43 AM:
I have a do loop in main form,I want to make the loop in another Thread ,butI failed With The way!Please help me!!Thanks!!! (If this comment was disrespectful, please report it.)
|
1/20/2005 7:26:06 AM: Srideep Prasad
You can make a routine on another thread.No problem about that...I will mail you shortly (If this comment was disrespectful, please report it.)
|
1/20/2005 8:23:39 PM:
Thanks for your letter! My question is described as follows in detail : I construct an active exe project with a main form,module and Class,There is a time-consuming do loop in member function of the class,My original idea is like that the do loop and main form should in different thread,but when excuting the do loop ,the main form is freezing,tell me why? is it the question that the priority of main thread is lower than the new thread? Are there good solutions?
(If this comment was disrespectful, please report it.)
|
1/25/2005 4:35:51 AM:
very fatally!run a time-consuming do loop in the Timer1_Timer event! the os crash! (If this comment was disrespectful, please report it.)
|
4/27/2006 11:10:11 AM: eBook Reviews
Srideep, you are a God of the written word. This is truly the best code I have ever used - and I’m not even exagurating.
However, I want to know 2 things... 1) How do you terminate a thread? 2) How do you send data from the master form to the thread? As far as I can see from the demo, you can only send data from the thread to the main app, not the other way round.
Again... you are awesome. (If this comment was disrespectful, please report it.)
|
5/2/2006 1:31:48 AM: Milind Patil
Hi, I created VB application communicate java application with multiple clients in VB 6.0 using Sockets. It is working properly. Now i want to modify this architecture like this one : Java Application -> VB ActiveX Exe -> Multiple VB Clients These multiple vb clients will communicate with VB ActiveX Exe and this ActiveX Exe will communicate with Java Application using Socket. There will not be any socket between VB ActiveX Exe and VB Clients. But inbetween Java Application and ActiveX exe, i want to use Socket. Is it possible ? (If this comment was disrespectful, please report it.)
|
2/22/2007 5:48:31 PM: Matt
I came across this while looking for a solution for some legacy VB6 code updates.
The solution calls for a thread to be created from a dll. It’s an activeX dll of course. However I saw sherwin said this didn’t work in a dll.
Is this true and is there a fix?
Thanks.
Great tutorial btw.
(If this comment was disrespectful, please report it.)
|
7/26/2007 6:34:09 PM: Jojo Rodriguez
Can you please tell me how this is different from running the same EXE file more than once? Isn't the new instance of the EXE file also run on a new thread?
Thanks. (If this comment was disrespectful, please report it.)
|
7/27/2007 10:25:23 AM: Jojo Rodriguez
I am trying to run at least 33 VB timers in one application using one single control array of timers. However only a few timers seem to be working at any given time. When I disable all timers, that is the time the seemingly inactive timers get triggered.
Why is this? Can your MThreadVB.dll solve my problem?
Thanks. (If this comment was disrespectful, please report it.)
|
8/20/2007 9:11:23 AM: Barcrest
Ok this works whn calling the forms within the main app, is there anyway to do it with a seperate application? I tried to split the code between 2 applications but it didn't work... Anyone got any ideas? Of should i move my sub application to be a another form off my main application like this example. (If this comment was disrespectful, please report it.)
|
Add Your Feedback
Your feedback will be posted below and an email sent to
the author. Please remember that the author was kind enough to
share this with you, so any criticisms must be stated politely, or they
will be deleted. (For feedback not related to this particular article, please
click here instead.)
To post feedback, first please login.
|