次の方法で共有


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

Comments

  • Anonymous
    May 12, 2006
    Calvin,

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

    ++Alan

  • Anonymous
    May 14, 2006
    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?

  • Anonymous
    May 15, 2006
    Good example, if you put this function as part native of VFP (Sedna), this was great feature.

  • Anonymous
    May 15, 2006
    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

  • Anonymous
    May 15, 2006
    The comment has been removed

  • Anonymous
    May 15, 2006
    BTW, what's the reason for calling LoadLibrary on User32? Isn't that available on the standard Win32API stack already?

  • Anonymous
    May 15, 2006
    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.

  • Anonymous
    May 15, 2006
    The comment has been removed

  • Anonymous
    May 16, 2006
    The comment has been removed

  • Anonymous
    May 16, 2006
    When I posted this Sample program to create multiple threads, I knew the inevitable follow-up question...

  • Anonymous
    May 16, 2006
    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.

  • Anonymous
    May 17, 2006
    The comment has been removed

  • Anonymous
    May 18, 2006
    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.

  • Anonymous
    May 18, 2006
    I need threading in VFP !

  • Anonymous
    May 24, 2006
    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?

  • Anonymous
    May 25, 2006
    DougBaker: yes: with hyperthreading or with multiprocessors, throughput can be much improved when there is little interthread resource contention

  • Anonymous
    June 13, 2006
    hi,Calvin_Hsia ^_^
    can you demo this code with vfp's form instead of messageboxA?
    thank you
    meimeib@126.com

  • Anonymous
    November 18, 2006
    Calvin, can you tell me how to run a EXE in a thread!

  • Anonymous
    November 22, 2006
    The comment has been removed

  • Anonymous
    February 15, 2007
    Hi, Calvin I need to run VFP's form look like !!meimeib!!. Can you tell me more. Thanks advance yothinin@hotmail.com

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

  • Anonymous
    May 18, 2008
    Need Salesmanwise Report program foxpro 2.6 dos mode, please send sample program my email address.

  • Anonymous
    November 02, 2008
    Do you like   ? May be you prefer  ? Specializes in quality  ? Don't beat me!

  • Anonymous
    January 17, 2009
    PingBack from http://www.hilpers.fr/496799-windows-server-2008-a/2

  • Anonymous
    January 20, 2009
    PingBack from http://www.hilpers.com/1068240-com-server

  • Anonymous
    May 18, 2009
    PingBack from http://blog.todmeansfox.com/2009/05/18/etl-subsystem-31-paralleling-and-pipelining/

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

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

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

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

  • Anonymous
    June 12, 2009
    The comment has been removed

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

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

  • Anonymous
    June 15, 2009
    The comment has been removed

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

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

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

  • Anonymous
    June 30, 2009
    The comment has been removed

  • Anonymous
    July 13, 2009
    Текст (слова) песни Ты проснешься на рассвете мы с тобою вместе встретим день рождения зари Как прекрасен этот мир посмотри как прекрасен этот мир Как прекрасен этот мир посмотри как прекрасен этот мир Ты не можешь не заметить соловьи живут на свете и простые сизари Как прекрасен этот мир посмотри как прекрасен этот мир Как прекрасен этот мир посмотри как прекрасен этот мир Ты взглянула и минуты остановлены как будто как росинки их бери Как прекрасен этот мир посмотри как прекрасен этот мир Как прекрасен этот мир посмотри как прекрасен этот мир Как прекрасен этот мир посмотри как прекрасен этот мир

  • Anonymous
    August 20, 2009
    Привет Помогите плиз, комп не включается, синий экран и всё :( Компьютерная помощь приезжали, винды переустановили - непомогает сейчас снова синий экран :(( Комп не трогал, все так и было... Или хотя бы куда обратится в Москве? Чтобы недорого.. Спасибо заранее!

  • Anonymous
    August 07, 2011
    Dear Calvin, I'm really courious about the sCode that you have been created. I want to know what is it? Because I never seen nothing like this before. Well, my question is: How can I do this assembly to pass it to a windows api?? What CHR() CODE i have to use?? Please, I Wait for your response.