Welcome to MSDN Blogs Sign in | Join | Help

Sample program to create multiple threads

I used the CreateThread call and the Heap functions to create a simple sample program that spawns a separate thread that displays a MessageBox

Try running it and you will see a MessageBox. However, unlike a normal MessageBox in your application, this one is on a separate thread, and thus the main thread can continue processing.

The code allocates some memory and writes some bytes of x86 machine code to execute. Those bytes simply put up the MessageBox and return.

The MessageBox strings need to be allocated and freed, and the strings and the code must not be freed until after the thread terminates by Returning.

 

 

 

 

 

CLEAR ALL

CLEAR

#define CREATE_SUSPENDED                  0x00000004

#define INFINITE            0xFFFFFFFF 

#define WAIT_TIMEOUT                     258

 

 

DECLARE integer LoadLibrary IN WIN32API string

DECLARE integer FreeLibrary IN WIN32API integer

DECLARE integer GetProcAddress IN WIN32API integer hModule, string procname

DECLARE integer CreateThread IN WIN32API integer lpThreadAttributes, ;

      integer dwStackSize, integer lpStartAddress, integer lpParameter, integer dwCreationFlags, integer @ lpThreadId

DECLARE integer ResumeThread IN WIN32API integer thrdHandle

DECLARE integer CloseHandle IN WIN32API integer Handle

DECLARE integer GetProcessHeap IN WIN32API

DECLARE integer HeapAlloc IN WIN32API integer hHeap, integer dwFlags, integer dwBytes

DECLARE integer HeapFree IN WIN32API integer hHeap, integer dwFlags, integer lpMem

DECLARE integer WaitForSingleObject IN WIN32API integer hHandle, integer dwMilliseconds

 

hModule = LoadLibrary("user32")

adrMessageBox=GetProcAddress(hModule,"MessageBoxA")

FreeLibrary(hModule)

 

hProcHeap = GetProcessHeap()

sCaption="This is a MessageBox running in a separate thread"+CHR(0)     && null terminate string

adrCaption = HeapAlloc(hProcHeap, 0, LEN(sCaption))   && allocate memory for string

SYS(2600,adrCaption,LEN(sCaption),sCaption)     && copy string into allocated mem

 

* int 3 = cc  (Debug Breakpoint: attach a debugger dynamically)

* nop = 90

* push 0  = 6a 00

* push eax = 50

* push 0x12345678 = 68 78 56 34 12

* ret 4 = c2 04 00

* mov eax, esp    = 8B c4

* mov eax, 0x12345678 = B8 78 56 34 12

* call eax  = ff d0

sCode=""

*sCode = sCode + CHR(0xcc)

sCode = sCode + CHR(0x6a) + CHR(0x00)     && push 0

sCode = sCode + CHR(0x68) + BINTOC(adrCaption,"4rs")  && push the string caption

sCode = sCode + CHR(0x68) + BINTOC(adrCaption,"4rs")  && push the string caption

sCode = sCode + CHR(0x6a) + CHR(0x00)     && push the hWnd

sCode = sCode + CHR(0xb8) + BINTOC(adrMessageBox,"4rs")     && move eax, adrMessageBox

sCode = sCode + CHR(0xff) + CHR(0xd0)     && call eax

sCode = sCode + CHR(0xc2)+CHR(0x04)+CHR(0x00)   && ret 4

 

AdrCode=HeapAlloc(hProcHeap, 0, LEN(sCode))     && allocate memory for the code

 

SYS(2600,AdrCode, LEN(sCode), sCode)      && copy the code into the string

 

dwThreadId =0

?"Starting thread count = ",GetThreadCount()

 

hThread = CreateThread(0,1024, AdrCode, 0, CREATE_SUSPENDED, @dwThreadId)

?"Thread handle = ",hThread

?"Thread ID = ", dwThreadID

ResumeThread(hThread)   && Start the thread

 

i=0

DO WHILE WaitForSingleObject(hThread, 100) = WAIT_TIMEOUT   && wait 100 msecs for the thread to finish

      ?i,"Current thread count",GetThreadCount()

      i=i+1

ENDDO

?"Final thread count = ",GetThreadCount()

 

 

 

 

?"Close",CloseHandle(hThread)

HeapFree(hProcHeap, 0, AdrCode)     && if the thread hasn't finished, we're releasing the executing code and it'll crash

HeapFree(hProcHeap, 0, adrCaption)

 

RETURN

 

 

PROCEDURE GetThreadCount as Integer

      *Use WMI to get process information

      objWMIService = GetObject("winmgmts:\\.\root\cimv2")

      colItems = objWMIService.ExecQuery("Select * from Win32_Process where processid = "+TRANSFORM(_vfp.ProcessId))

      For Each objItem in colItems

            nRetval = objItem.ThreadCount

      NEXT

      RETURN nRetval

 

Published Thursday, May 11, 2006 11:51 AM by Calvin_Hsia

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Sample program to create multiple threads

Friday, May 12, 2006 8:41 AM by Alan Stevens
Calvin,

This is very cool!  Please expand on this in Sedna, so we can launch multiple threads in VFP.

++Alan

# re: Sample program to create multiple threads

Monday, May 15, 2006 1:10 AM by Janusz Czudek
Great sample, but can we run a foxpro code on the new thread?

We have to get a pointer (AdrCode) to foxpro procedure/function and pass it to CreateThread()...

Is there a way to get such pointer?

# re: Sample program to create multiple threads

Monday, May 15, 2006 9:34 AM by Franklin Garón
Good example, if you put this function as part native of VFP (Sedna), this was great feature.

# re: Sample program to create multiple threads

Monday, May 15, 2006 11:54 AM by Calvin_Hsia
Alan, Jausz, Franklin: If you could run VFP code on multiple threads, what scenarios will this enable for you? How will you use it?

thanks

# re: Sample program to create multiple threads

Monday, May 15, 2006 7:38 PM by Rick Strahl
Calvin,

I also posted a few .NET examples that do something similar and I actually think that using .NET in that situation is easier. The other advantage of using .NET in thi scenario is that you could call a Visual FoxPro COM component from the multithreaded code - in fact I showed how to do this in a recent article with a generic COM callable .NET component that can execute another COM component which can be VFP created.

http://www.west-wind.com/presentations/dotnetfromVfp/DotNetFromVfp_MultiThreading.asp

Multi-threading can come in very handy in a number of situations. Send and forget operation of a lengthy task. In Web applications Aysnc tasks can be used to fire of a long running task and provide feedback so the Web client can see progress information. Offloading blocking user interfaces (while downloading a file for example) is another where I use multi-threading often...

It would be very cool if there was a way for VFP to create a new thread and then call back into FoxPro code. In fact I seem to remember I played with that a few years ago with the FoxPro library kit, but it wasn't very happy when the call returned on a new thread <g>.

# re: Sample program to create multiple threads

Monday, May 15, 2006 7:40 PM by Rick Strahl
BTW, what's the reason for calling LoadLibrary on User32? Isn't that available on the standard Win32API stack already?

# re: Sample program to create multiple threads

Monday, May 15, 2006 9:00 PM by Calvin_Hsia
In this sample, LoadLibrary for User32.dll is needed because the return value is passed to GetProcAddress. You’re right that User32.dll is already loaded, so LoadLibrary doesn’t have to *load* the DLL: it just returns the hModule (which is the module address).

See next blog post for sample that calls VFP code in a thread proc.

# re: Sample program to create multiple threads

Tuesday, May 16, 2006 6:02 AM by Dimitrios Papadopoulos
Calvin,

it would be great if you could run fox code in different threads. Actually my scenarios are more or less as Rick's. Here are some scenarios which I would use this option for :
a. I am running a remote - or local - sql query, or queries against several remote databases which at the end the different cursor resultsets must be localy joined. The queries take long because of complexity but the result sets are just a few records ..., asynchronous sqlexec does not help in this case.
b. I have a service that downloads - in a loop - and parses web pages from several different slow web sites. In order to proceed to the next download the program has to wait the previous ...
c. There are issues with timers also that can be improoved by using multithreading. To be able to have different timers in an application that run code at the same time...

# re: Sample program to create multiple threads

Tuesday, May 16, 2006 11:47 AM by Jochen Kirstaetter
Thanks for this article, Calvin.
Threading is very powerful and as Rick already stated in his comment as well as in his blog articles. Threading in VFP would be very productive in case of long-term processes. We have several customer projects with huge data processing - monthly/quarterly/yearly billing runs - with about 1.5GB data. So, if the customer starts this process the machine is blocked for approx. 2 hours (depending on the number of clients being processed). So, if we could fork those runs on a separate thread, it would be a lot easier for us *not to block* the application and just show an indicator on a dialog or status bar.

Same for background downloads and other stuff like this.

So, in my opinion Threading would be a boost for VFP! Today I'm using a .NET based launcher for COM servers like Rick. But a native solution would be more interesting.


Kind regards, JoKi

# Create multiple threads from within your application

Tuesday, May 16, 2006 2:01 PM by Calvin Hsia's WebLog
When I posted this Sample program to create multiple threads, I knew the inevitable follow-up question...

# re: Sample program to create multiple threads

Tuesday, May 16, 2006 10:50 PM by Franklin Garzón
If, the colleagues have exposed the principal points for which to implement the MH in VFP as a native part, another case is that nowadays on having executed a process of connection to a WS the machine freezes waiting for the process of response.

# re: Sample program to create multiple threads

Wednesday, May 17, 2006 1:06 PM by Craig Larson
I'm wondering if the majority of users just need a box message to pop up informing them that some process is happening and will be available shortly, would this not be a simpler solution?

** C++ code below **

#include "pro_ext.h"
#include <string.h>

char FAR mmsg[254];

DWORD WINAPI FAR Message(LPVOID aVoidPointer)
{
MessageBox(NULL, mmsg, "Separate Thread Support",NULL);
return (0);
}

void FAR mbox(ParamBlk FAR *parm) // the function definition
{
DWORD ThreadId;

char FAR *msg;

msg = ((char FAR *) _HandToPtr(parm->p[0].val.ev_handle));

strncpy(mmsg, msg, strlen(msg));

CreateThread(NULL,0, Message, 0, 0, &ThreadId);  //show messagebox in separate thread
_RetLogical(1); //return .T.
}

FoxInfo myFoxInfo[] ={
{"MBOX", (FPFI) mbox, 1, "C"},
};

extern "C" FoxTable _FoxTable = {
(FoxTable FAR *)0, sizeof(myFoxInfo)/ sizeof(FoxInfo), myFoxInfo
};


** Fox Code Below **
SET LIBRARY TO meep
_result = .F.

_result = mbox("Messagebox in separate thread")

FOR _cnt = 1 TO 5
WAIT WINDOW "Count = " + STR(_cnt) TIMEOUT 1
ENDFOR

IF (_result)
WAIT WINDOW "MessageBox Was Displayed" nowait
ENDIF

# re: Sample program to create multiple threads

Thursday, May 18, 2006 7:44 PM by Olaf Doschke
This is nice in showing, that MT is even possible with some API calls. But the last time I poked some assembler into memory was with the commodore vc 20, not even c64, even with that oldie one could use an assembler :^).

How would we use MT within VFP?

1. using API calls with a callback function like MoveFileWithProgress().

2. nonblocking wait for external processes: Multiple file download, mail sending, COM port polling, whatever.
Especially in case of the failure of an external process, with a separate thread a timeout is much easier, and that thread may die without affecting the main thread.

3. putting lengthy porcesses in the background, like backup of large amounts of files, lenghty complex queries (datamining).

4. seperating tasks into smaller portions being able to run parallel in principle.
For example with shared memory access, one thread may fill a buffer by reading in a file, one thread may process it (eg compress blocks), the next thread writes the processed data back to disk.
All this may be done step by step in a single thread, but seperating these three tasks could make use of multiple cpu cores and balance cpu needs.

5.,6.,7.,8.,9.,... what I even did not think about now.

Bye, Olaf.

# re: Sample program to create multiple threads

Friday, May 19, 2006 5:40 AM by Martin Bauer
I need threading in VFP !

# re: Sample program to create multiple threads

Wednesday, May 24, 2006 10:13 PM by DOUGBAKER
Well, I recently upgraded my workstation to a fast processor with hyper threading. When I run some processes, one virtual processor is maxed, the other one is not doing much. If I could create multiple threads, my hunch is the processor would use hyper threading to run both threads. If I can design the threads to not be dependent on each other,  would  I get faster throughput?

# re: Sample program to create multiple threads

Thursday, May 25, 2006 3:40 PM by Calvin_Hsia
DougBaker: yes: with hyperthreading or with multiprocessors, throughput can be much improved when there is little interthread resource contention

# re: Sample program to create multiple threads

Wednesday, June 14, 2006 3:44 AM by meimeib
hi,Calvin_Hsia ^_^
can you demo this code with vfp's form instead of messageboxA?
thank you
meimeib@126.com

# re: Sample program to create multiple threads

Saturday, November 18, 2006 3:04 PM by jimsun

Calvin,

can you tell me how to run a EXE in a thread!

# re: Sample of easy programs of foxpro with problems

Thursday, November 23, 2006 2:22 AM by noel

can you give me an easy sample of database programs with problems and foxpro with problems i ned it for my project.......... just send to this e-mail guitarsound_music@yahoo.com thanks im hoping for your rply as soon as posible thank you.....

# re: Sample program to create multiple threads

Thursday, February 15, 2007 9:14 AM by yothinin

Hi, Calvin

I need to run VFP's form look like !!meimeib!!. Can you tell me more.

Thanks advance

yothinin@hotmail.com

# How to interrupt your code

Thursday, May 15, 2008 10:43 PM by Calvin Hsia's WebLog

I received a question: Simply, is there a way of interrupting a vfp sql query once it has started short

# re: Sample program to create multiple threads

Sunday, May 18, 2008 8:35 AM by raja

Need Salesmanwise Report program foxpro 2.6 dos mode, please send sample program my email address.

# Spammy mommy

Monday, November 03, 2008 4:44 AM by !saubbesia!

Do you like   ?

May be you prefer  ?

Specializes in quality  ?

Don't beat me!

# Windows SERVER 2008 - Page 2 | hilpers

Sunday, January 18, 2009 7:05 AM by Windows SERVER 2008 - Page 2 | hilpers

# COM-Server | hilpers

Tuesday, January 20, 2009 9:18 AM by COM-Server | hilpers

# ETL Subsystem 31: Paralleling and Pipelining &laquo; Tod means Fox

# re: Sample program to create multiple threads

Thursday, June 11, 2009 9:50 PM by 出会い

ヒマだょ…誰かかまってぉ…会って遊んだりできる人募集!とりあえずメール下さい☆ uau-love@docomo.ne.jp

# re: Sample program to create multiple threads

Friday, June 12, 2009 9:37 PM by 小向美奈子

話題の小向美奈子ストリップを隠し撮り!入念なボディチェックをすり抜けて超小型カメラで撮影した神動画がアップ中!期間限定配信の衝撃的映像を見逃すな

# 小向美奈子盗撮

Friday, June 12, 2009 9:57 PM by 小向美奈子

話題の小向美奈子ストリップを隠し撮り!入念なボディチェックをすり抜けて超小型カメラで撮影した神動画がアップ中!期間限定配信の衝撃的映像を見逃すな

# re: Sample program to create multiple threads

Friday, June 12, 2009 10:06 PM by 小向美奈子

話題の小向美奈子ストリップを隠し撮り!入念なボディチェックをすり抜けて超小型カメラで撮影した神動画がアップ中!期間限定配信の衝撃的映像を見逃すな

# 一般人とは違う価値観

Saturday, June 13, 2009 3:59 AM by セフレ

女性のオナニーをお手伝いして、謝礼をもらうお仕事を始めませんか?

# re: Sample program to create multiple threads

Saturday, June 13, 2009 9:49 PM by 家出掲示板

カワイイ子ほど家出してみたくなるようです。家出掲示板でそのような子と出会ってみませんか?彼女たちは夕食をおごってあげるだけでお礼にHなご奉仕をしてくれちゃったりします

# re: Sample program to create multiple threads

Sunday, June 14, 2009 10:00 PM by 右脳左脳

あなたは右脳派?もしくは左脳派?隠されたあなたの性格分析が3分で出来ちゃう診断サイトの決定版!合コンや話のネタにも使える右脳左脳チェッカーを試してみよう

# re: Sample program to create multiple threads

Monday, June 15, 2009 9:16 PM by セレブラブ

セレブラブでは性欲のある男性を募集しています。セフレパートナーを探している20代・30代の女性たちが多数登録されています。セレブと遊びたい、Hがしたいという方は無料登録からどうぞ

# re: Sample program to create multiple threads

Tuesday, June 16, 2009 9:19 PM by 逆援助

セレブ達は一般の人達とは接する機会もなく、その出会う唯一の場所が「逆援助倶楽部」です。 男性はお金、女性はSEXを要求する場合が多いようです。これは女性に圧倒的な財力があるから成り立つことの出来る関係ではないでしょうか?

# re: Sample program to create multiple threads

Wednesday, June 17, 2009 9:12 PM by 救援部

貴方のオ○ニーライフのお手伝い、救援部でHな見せたがり女性からエロ写メ、ムービーをゲットしよう!近所の女の子なら実際に合ってHな事ができちゃうかも!?夏に向けて開放的になっている女の子と遊んじゃおう

# re: Sample program to create multiple threads

Thursday, June 18, 2009 9:50 PM by 出会い

まったぁ〜りしたデートがしたいです☆結構いつでもヒマしてます♪ m-g-j@docomo.ne.jp 年齢と名前くらいは入れてくれるとメール返信しやすいかも…

# Фильмы 2009

Wednesday, July 01, 2009 3:43 AM by filmmy

Нашел сайт в сети  http://filmy.my1.ru/, где Вы сможете найти множество интересных материалов. Здесь можна посмотреть кино разных жанров в режиме онлайн, а можна и скачать фильмы, причем совершенно бесплатно.

Для любителей легкой эротики есть два раздела: эротика онлайн и скачать эротику,

<a href="http://filmy.my1.ru/">Фильмы онлайн, скачать фильмы</a>.

# как прекрасен этот мир. пасматри !!!

Monday, July 13, 2009 8:47 AM by Iterbintuit

Текст (слова) песни

Ты проснешься на рассвете мы с тобою вместе встретим день рождения зари

Как прекрасен этот мир посмотри как прекрасен этот мир

Как прекрасен этот мир посмотри как прекрасен этот мир

Ты не можешь не заметить соловьи живут на свете и простые сизари

Как прекрасен этот мир посмотри как прекрасен этот мир

Как прекрасен этот мир посмотри как прекрасен этот мир

Ты взглянула и минуты остановлены как будто как росинки их бери

Как прекрасен этот мир посмотри как прекрасен этот мир

Как прекрасен этот мир посмотри как прекрасен этот мир

Как прекрасен этот мир посмотри как прекрасен этот мир

# Компьютерная помощь

Thursday, August 20, 2009 11:50 PM by logginnoff

Привет

Помогите плиз, комп не включается, синий экран и всё :(

Компьютерная помощь приезжали, винды переустановили - непомогает

сейчас снова синий экран :((

Комп не трогал, все так и было...

Или хотя бы куда обратится в Москве? Чтобы недорого..

Спасибо заранее!

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker