Jump to content
Sign in to follow this  
Zohar

[Closed] How to Run a Function As a Seperate Thread/Process?

Recommended Posts

Zohar

Hi

 

If You have some function that is long and continuous, and you want to run it in a seperate way from your script, so it will not block it,

then you can do this:

1) Take it out of your script, and put it in a seperate code file,

2) Run that code file seperately, for example via

Run(@AutoItExe&" "&$Script_FullPath)

This will make the code run in a seperate Process, and so it will run in parallel to your main script, not blocking it.

 

My question is:

Is it possible to do this more simply, without needing to move the function to a seperate code file?

Maybe some Function in AutoIt exists, that gets 1 parameter which is a FunctionName, and then runs that function seperately?

 

Thank you

Zohar

Edited by Zohar
  • Like 1

Share this post


Link to post
Share on other sites
AdmiralAlkex

Is it possible to do this more simply, without needing to move the function to a seperate code file?

Well there's always NOT putting it in a separate file. But you will have to decide if that's easier for you.

If $CmdLine[0] > 0 And $CmdLine[1] = "Bordsdricka" Then
    _Test()
    Exit
EndIf

HotKeySet("O", _Hot)

Sleep(999999)

Func _Hot()
    If @Compiled Then
        Run(@AutoItExe & ' Bordsdricka')
    Else
        Run(@AutoItExe & " " & FileGetShortName(@ScriptFullPath) & ' Bordsdricka')
    EndIf
EndFunc

Func _Test()
    MsgBox(0, "Message from _Test", "Bananas")
EndFunc

Share this post


Link to post
Share on other sites
Zohar

Hi AdmiralAlkex

 

Interesting workaround,

tho not exactly simplifying things :)

 

Maybe there's already a Fucntion in AutoIt that does what I asked about?

something like

RunAFunctionAsASeparateThread($FunctionName)

or

RunAFunctionAsASeparateProcess($FunctionName)

?

Edited by Zohar

Share this post


Link to post
Share on other sites
BrewManNH

AutoIt is single threaded, so you can't do it in the same script.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
nullschritt

As stated autoit is single-threaded. The best way to use more than one thread for processing data is using, is to use command line sparrmaters to launch extra copies of your script, each doing what you need. You can have it return the data to the main thread through Inter-Process Communication. There are many methods of doing this. The simplest and slowest is writing to a database or file.

  • Like 1

Share this post


Link to post
Share on other sites
Zohar

Thank you both.

What I am doing is not multithreading..

More like multi-process :), since it creates another process...

 

That's because I put the function in a seperate au3 code file, and then run it.

 

It works and it ahieves what I need,

however I thought maybe there's a way to simplify it.. from the developer side - my side.

Instead of everytime creating a seperate code file when needing this parallel work,

It could've been nice if AutoIt had a unction called RunAsASeperateProcess($FunctionName),

which will achieve, the same as what I do now(by moving the code to a separate code file and running it), without moving it to a separate file.

 

Maybe the developers can consider this as a new function?

Edited by Zohar

Share this post


Link to post
Share on other sites
nullschritt

@zohar, this function wont be added, because it can already be achieved in auto-it EASILY. Just like AdmiralAlkex showed you. you put the function you want to call inside a command line switch, then launch the script with the command line option. A new process will be opened from the same file, but only the specified function will run.

Share this post


Link to post
Share on other sites
jchd

These don't make AutoIt any more threadsafe, just because some naïve people mislead themselves and others thinking they can do that by pure magic. All one can do is discover creative and unsuspected ways to shoot oneself in the foot.

AutoIt is not threadsafe and no amount of gift wrap or holy water will make it such. Period.

Anyway, threads are evil.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
Zohar

@zohar, this function wont be added, because it can already be achieved in auto-it EASILY. Just like AdmiralAlkex showed you. you put the function you want to call inside a command line switch, then launch the script with the command line option. A new process will be opened from the same file, but only the specified function will run.

 

Yes,

I understand it.

But you do understand that when you use this workaround, you then block your command line from being used for other stuff..

 

quick forum search for "multithread" shows these promising works:

'?do=embed' frameborder='0' data-embedContent>>

'?do=embed' frameborder='0' data-embedContent>>

and more...

 

Hi Orbs

It is nice, but I am not looking for MultiThreading,

just to create another (long) process which will happen in parallel.

(and to achieve it in a simpler way that what I use now)

 

These don't make AutoIt any more threadsafe, just because some naïve people mislead themselves and others thinking they can do that by pure magic. All one can do is discover creative and unsuspected ways to shoot oneself in the foot.

AutoIt is not threadsafe and no amount of gift wrap or holy water will make it such. Period.

Anyway, threads are evil.

 

But this is Multi-Process, not multi-threading.

And yes, as all developers, I am aware of the disadvantages of multithreading.

Share this post


Link to post
Share on other sites
AdamUL

But you do understand that when you use this workaround, you then block your command line from being used for other stuff.

This is not a true statement.  Use the command line to your advantage with switches for the functions that you want to execute, not just feeding the command line a script. > Mat's Command Line UDF is also useful for this.  If you have other command line switches, keep the ones for re-execution private, like when you write a UDF with internal functions.  

 

Have a look at this stripped down example, from one of my old projects, where I used multiple functions that were run in a different process using the command line and re-execution.  I didn't use Mat's UDF with this project.  

 

#include <ClipBoard.au3>

If StringInStr($CmdLineRaw, '/MsgBoxData;') Then ;Creates Return Message boxes.
    Opt("TrayIconHide", 1) ;Hide tray icon for rerun script that shows the Message box.
    $CmdLineRaw = StringSplit(StringMid($CmdLineRaw, StringInStr($CmdLineRaw, '/MsgBoxData')), ';')
    Global $aMsgBoxData = StringSplit($CmdLineRaw[2], "|")
    Switch $aMsgBoxData[0]
        Case 3
            MsgBox($aMsgBoxData[1], $aMsgBoxData[2], $aMsgBoxData[3])
        Case 4
            MsgBox($aMsgBoxData[1], $aMsgBoxData[2], $aMsgBoxData[3], $aMsgBoxData[4])
        Case 5
            MsgBox($aMsgBoxData[1], $aMsgBoxData[2], $aMsgBoxData[3], $aMsgBoxData[4], $aMsgBoxData[5])
    EndSwitch
    Exit
ElseIf StringInStr($CmdLineRaw, '/MonDialog:') Then ;Monitor HotKeys for Return Dialog boxes.
    Opt("TrayIconHide", 1) ;Hide tray icon for rerun script that reads Dialog.
    $CmdLineRaw = StringSplit(StringMid($CmdLineRaw, StringInStr($CmdLineRaw, '/MonDialog')), ':')
    HotKeySet("^!n", "_CopyToClipboard")
    HotKeySet("^!b", "_CopyToClipboard")
    HotKeySet("^!s", "_CopyToClipboard")
    HotKeySet("^!p", "_CopyToClipboard")
    HotKeySet("^!i", "_CopyToClipboard")
    HotKeySet("^!m", "_CopyToClipboard")
    HotKeySet("^!u", "_CopyToClipboard")
    While ProcessExists($CmdLineRaw[2])
        Sleep(50)
    WEnd
    Exit
 EndIf

Global $sDefaultValue = ""
Global $sInputBoxAnswer
Global $iError
Global $sMsgBoxData
Global $iReturnBoxPID
Global $sReturnBoxPIDs
Global $aReturnBoxPIDs
Global $aWinPos
Global $iStartHotKey

While 1
    $sInputBoxAnswer = InputBox("This is a test", "Please Enter Something.", $sDefaultValue, "","150","140")
    $iError = @error
    Select
        Case $iError = 0 ;OK - The string returned is valid

        Case $iError = 1 ;The Cancel button was pushed
            ExitLoop
        Case $iError = 3 ;The InputBox failed to open
            MsgBox(16,"ERROR","Input Box would not open.")
            ExitLoop
    EndSelect

    $sInputBoxAnswer = StringUpper($sInputBoxAnswer)
    If StringInStr($sInputBoxAnswer, ";") Then
        $sInputBoxAnswer = StringReplace($sInputBoxAnswer, ";", "-")
    EndIf
    $sDefaultValue = $sInputBoxAnswer
    
    $sMsgBoxData = "Data Entered in InputBox: " & @CRLF & @CRLF & $sInputBoxAnswer
    
    $iReturnBoxPID = _MsgBoxEx(0, $sInputBoxAnswer, $sMsgBoxData)
    $sReturnBoxPIDs &= $iReturnBoxPID & "|"
    
    Opt("WinTitleMatchMode", 3)
    WinWait($sInputBoxAnswer)
    $aWinPos = WinGetPos($sInputBoxAnswer)
    WinMove($sInputBoxAnswer, "", $aWinPos[0] + 250, $aWinPos[1] - 100)
    
    $iStartHotKey += 1
    If $iStartHotKey = 1 Then _MontorReturnDialog()

WEnd

$aReturnBoxPIDs = StringSplit(StringTrimRight($sReturnBoxPIDs, 1), "|")

For $iPID = 1 To $aReturnBoxPIDs[0] Step 1
    ProcessClose($aReturnBoxPIDs[$iPID])
Next

Func _CopyToClipboard()
    Local $sReadText = WinGetText("[active]")
    If StringInStr($sReadText, "Data Entered in InputBox: ") Then
        _ClipBoard_Empty()
        _ClipBoard_Open(0)

        Local $aReadText = StringSplit(StringTrimLeft(StringStripWS($sReadText, 3), 3), @CRLF & @CRLF, 1)
        
        Local $aDataPulled
        Switch @HotKeyPressed
            Case "^!n"
                _ClipBoard_SetData(WinGetTitle("[active]") )
            Case "^!b"
                $aDataPulled = StringSplit($aReadText[1], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
            Case "^!s"
                $aDataPulled = StringSplit($aReadText[2], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
            Case "^!p"
                $aDataPulled = StringSplit($aReadText[3], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
            Case "^!i"
                $aDataPulled = StringSplit($aReadText[4], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
            Case "^!m"
                $aDataPulled = StringSplit($aReadText[5], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
            Case "^!u"
                $aDataPulled = StringSplit($aReadText[6], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
            Case Else
                $aDataPulled = StringSplit($aReadText[5], ": ", 1)
                _ClipBoard_SetData($aDataPulled[2])
        EndSwitch

        _ClipBoard_Close()
    EndIf
EndFunc

Func _MsgBoxEx($iFlag, $sTitle, $sText, $iTimeOut = 0, $iHwnd = 0) ;Show a message box for the data.
    Local $sMsgBoxDataEx
    If $iTimeOut = 0 And $iHwnd = 0 Then
        $sMsgBoxDataEx = $iFlag & '|' & $sTitle & '|' & $sText
    ElseIf $iTimeOut <> 0 And $iHwnd = 0 Then
        $sMsgBoxDataEx = $iFlag & '|' & $sTitle & '|' & $sText &'|' & $iTimeOut
    Else
        $sMsgBoxDataEx = $iFlag & '|' & $sTitle & '|' & $sText & '|' & $iTimeOut & '|' & $iHwnd
    EndIf
    
    Return _ReRunScript('/MsgBoxData;' & $sMsgBoxDataEx)

EndFunc

Func _MontorReturnDialog() ;Monitor Return Dialog for HotKeys.
    Return _ReRunScript('/MonDialog:' & @AutoItPID)
EndFunc
 
 Func _ReRunScript($sCmdLine)
    If @Compiled Then
         Return(Run(@ScriptFullPath & ' ' & $sCmdLine))
    Else
         Return(Run(@AutoItExe & ' "' & @ScriptFullPath & '" ' & $sCmdLine))
    EndIf
 EndFunc

 

 

Adam

Share this post


Link to post
Share on other sites
Zohar

I see..

Thank you.

 

I think for the simplicity of code, I will not use the command line trick this time,

and simply copy to a seperate code file..

But I might use it in the future.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.