TheDcoder

_Singleton Generates Multiple Objects!

15 posts in this topic

Hello :bye:, Please look at the code below:

; This is not the real script that I use for my project!!! This decoy script helps you understand better ;)

#include "Misc.au3"

Global $sProgramIdentifier

Func Test($sIdentifier)
    $sIdentifier = $sProgramIdentifier
    Switch _Singleton($sProgramIdentifier, 1)
        Case 0
            MsgBox(64, "Testing, Testing", "Its working!!")
        Case Else
            MsgBox(64, "Testing, Testing", "Its not working!!")
    EndSwitch
EndFunc

Test("Lick the lemon")

Save this to a file and run it, you will get a MsgBox telling "Its not working!!"

Again, Run the script a second-time without closing the first MsgBox and you will again get a MsgBox telling the same thing!! This was not supposed to happen :(

How can I get the MsgBox telling that it works :unsure:?

Thanks In Advance, TD :)


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites



You are overwriting the passed parameter with the global variable,  which I suspect is the opposite of what you intended. 

Share this post


Link to post
Share on other sites

TheDcoder,

And referencing this thread, you are generating multiple instances, not multiple objects. ;)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

@Danp2 Overwritten or not, but the content does not change, does it? ;)

@Melba23 I don't quite understand the difference "instances" & "objects" here, please explain :)

TD


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

TheDcoder,

Multiple instances are where the same app is running several times at the same time. You can see this with SciTE using the check.if.already.open option - if not set (which is the default SciTE4AutoIt3 setting) each file is opened in a new tab; if set each file is opened in a new instance of SciTE. Give it a try and see - but add the line to your User Properties file so you can delete it once you have tested. :)

Objects are something entirely different - and I suggest you do what >JohnOne suggested and do some Google research for yourself. You might want to start here. ;)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

@Melba23 I know what instances are, but in this case _singleton should return 0 because there are multiple instances (like in the example for _Singleton). I wanna know why _Singleton is retuning multiple mutex(es) instead of 0

TD :)

P.S Thanks for the wiki link

Edited by TheDcoder

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

#7 ·  Posted (edited)

TheDcoder,

_Singleton depends on you passing something which can create a mutex object which is then used to flag whether it is currently in use. In the script you posted, the string used by _Singleton to generate the mutex is empty - which from my limited knowledge means that the whole system falls over. If you assign a proper string to the mutex like this:

Global $sProgramIdentifier = "fred"
then the mutex object is successfully created and the second instance does indeed return "Its working!!". ;)

And anyway, why are you using a function parameter which you immediately reassign within the function? It makes no sense at all. :wacko:

M23

Edited by Melba23
Fixed tags

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

And anyway, why are you using a function parameter which you immediately reassign within the function? It makes no sense at all. :wacko:

You will get to know it soon :D

 

$sIdentifier = $sProgramIdentifier

Doesn't this line assign the variable a value?

TD :)


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

TheDcoder,

Indeed it does - but the question is why you are immediately reassigning a function parameter to a Global variable. You use parameters to pass specific values to a function, or to assign default values if no parameter is passed. If you want to use a Global variable inside a function, then there is no point in doing what you did - just use the variable directly. :)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Thanks Melba!

This code works:

; NOTE: Removed line no.6 & modified line no.7 in the previous code :)

#include "Misc.au3"

Func Test($sIdentifier)
    Switch _Singleton($sIdentifier, 1)
        Case 0
            MsgBox(64, "Testing, Testing", "Its working!!")
        Case Else
            MsgBox(64, "Testing, Testing", "Its not working!!")
    EndSwitch
EndFunc

Test("Lick the lemon")

TD :D

P.S I still wonder why my first code doesn't work >_<


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

TheDecoder,

 

I still wonder why my first code doesn't work

I thought I had already explained that. :)

You were resetting the function parameter which you use to create the mutex to the value of an undefined Global variable - mutexes need a string to work, so passing an empty string meant that the function would fail. ;)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

@Melba23 Erm.... Why does this line:


$sIdentifier = $sProgramIdentifier

Not pass the string??


AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

Share this post


Link to post
Share on other sites

It does pass it and it is empty, lets try this a third time "Empty strings dont work!"  

Global $sProgramIdentifier
 
$sProgramId2 = ""
 
_test($sProgramIdentifier , $sProgramId2)
 
 
Func _test($sParam1 , $sParam2)
 
If $sProgramId2 == $sProgramIdentifier Then msgbox (0, '' , "those are the same thing and neither will work")
 
EndFunc
 
 

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Share this post


Link to post
Share on other sites

@Melba23 Erm.... Why does this line:

$sIdentifier = $sProgramIdentifier

Not pass the string??

 

You are overwriting the passed parameter with the global variable,  which I suspect is the opposite of what you intended. 

 

This is what I tried to point out in my initial post. Let's break this down into simple steps:

  • You declare a global variable named $sProgramIdentifier, but never assign it a value
  • You call the function Test with the parameter "Lick the lemon"
  • The string gets stored into the variable $sIdentifier
  • You overwrite the value of $sIdentifier ("Lick the lemon") with the value of $sProgramIdentifier (Undefined)

Can you explain the intended purpose of the global variable? Is it supposed to contain the most recent value passed to the Test function? 

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

  • You overwrite the value of $sIdentifier ("Lick the lemon") with the value of $sProgramIdentifier (Undefined)

:idea: Sorry all, What I thought is:

$sIdentifier = $sProgramIdentifier

  ---------------->  = ----------------->

But I forgot that

<--------------- = <--------------------

Thanks, TD :)

Edit: Completed the post (pressed the submit button mistakenly)

Edit 2: Comma

Edited by TheDcoder

AutoIt.4.Life Clubrooms - Life is like a Donut (secret key)

Spoiler

My contributions to the AutoIt Community

Some messages & Apologizes:

If I hurt you, Please accept my apologies, I never (regardless of the situation) mean to hurt anybody!!!

Also, I am very busy with my project so I will appear in the last row of the online list, if you want to contact me: Email@TheDcoder.xyz

Or you can have a nice chat with me in freenode, I use the same nick on freenode too!

3fHNZJ.gif

PLEASE JOIN ##AutoIt AND HELP THE IRC AUTOIT COMMUNITY!

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

  • Similar Content

    • n3wbie
      By n3wbie
      i Tried Using Function _single ton
      It Works Like Charm on same computer
      But it is unable to catch up when 2 instance of exe are launched in lan pc
      I would also like to know if there was a way to make particular number of instance work like allow 4-5 instance of same exe to run
    • TheSaint
      By TheSaint
      This is just a little helpful script, that I started using a month or so ago (one program so far), with this version having a Restore ability added (so now using with two programs of mine, as of tonight).
      You can find other alternatives or similar scripts here, the most recent being - _SingleScript
      guinness also has something much more elaborate, that is well worth checking out - _SingletonHWID.
      Just place the following at the beginning of your script, and adjust where needed and wanted (including Scriptname, variable names and MsgBox magic numbers, etc). Perhaps you should read and use the following - Best coding practices ... unlike my slack hobby programmer self (not always).
      #include <Misc.au3> Global $ans, $exe, $handle, $pid, $script, $Scriptname, $status, $w, $wins ; Assign the program name (window title). $Scriptname = "Update Mp3 Artwork v7.9 (updated December 2015)" ; The following line both sets the unique ID of the current program, plus queries if a program with the same ID is running already. $status = _Singleton("update-mp3artwork-thsaint", 1) If $status = 0 Then ; A program with the same ID is already running. ; Assign a PID for previous script, based on current executable name, whether current script is compiled or not, and assign the executable name. If @Compiled = 1 Then $pid = ProcessExists(@ScriptName) $exe = @ScriptName Else $pid = ProcessExists("AutoIt3.exe") $exe = "AutoIt3.exe" EndIf ; Assign a PID for current script. $script = @AutoItPID ; $ans = MsgBox(262177, "Close Running Instance Query", _ "'Update Mp3 Artwork' program is already running." & @LF & @LF & _ "Do you want to close it for another instance?" & @LF & @LF & _ "NOTE - If all work has been saved, and you are" & @LF & _ "trying to work on another album, then a click on" & @LF & _ "OK is recommended, else just click CANCEL, to" & @LF & _ "attempt a restore or re-activate of original." & @LF & @LF & _ $pid & " (" & $exe & ") " & $script & @LF & @LF & _ "(will default to CANCEL in 30 seconds)", 30) If $ans = 1 Then ; Attempt to close original instance, and continue with new. If $pid <> $script Then ProcessClose($pid) Else MsgBox(262192, "Close Error", "OK process failed!", 0) Exit EndIf ElseIf $ans = 2 Or $ans = -1 Then ; Attempt to retore and activate a non-active or minimized window. ; Get a list of all running programs with the same name. $wins = WinList($Scriptname, "") ; Loop through found instances and compare PID's, restoring or re-activating any match. For $w = 1 to $wins[0][0] $handle = $wins[$w][1] If WinGetProcess($handle, "") = $pid Then WinSetState($handle, "", @SW_RESTORE) WinActivate($handle, "") ExitLoop EndIf Next Exit EndIf EndIf Enjoy!
      P.S. I have a couple of programs that I regularly forget are minimized while working with another related one, so this saves me some mucking around to close and restart or restore etc. Pretty basic, but does the job well so far.
    • explorerpl
      By explorerpl
      Hi. I'm a teacher and I do a lot of tutorials and other presentations on my computer. I've developed a tool using AutoIt and Adobe AIR to display all the shortcuts I use while I'm presenting. According to the forum rules this would mean that I've developed a keylogger, so I can't show any of the code, but I'm still hoping someone will help me solve an issue I'm having - a memory leak (or at least I think that's it).
      I can see the application is taking up more and more memory, but it never goes super crazy. I think it was at 25 MB at one point and that was it. However I see that the longer the application is running less responsive it is. It doesn't capture all the events, or it simply lags. 
      I'm using AssocArrays and _MouseOnEvent UDFs, _WinAPI_SetTimer, _WinAPI_SetWindowsHookEx, _Singleton and TCP. I've done some research before posting this and I know there are some issues in special cases, but all solutions were "code specific". Since I can't post any of the code I couldn't respond in those threads. Other than that it really doesn't seem to be the problem with any of the UDFs, so my question is:
      Is this a memory leak? If so how can I find it and remove it? What to do to avoid it in the future.
      I understand that declaring variables over and over (something in the timer) may be the cause of this, so according to what I've read on the forum I've changed the variables to Global and moved them outside the functions. That way they are only declared once, and then only values are being reassigned. That unfortuantly didn't help. Is there anything else I could do or look for?
      BTW - I've used Adobe AIR to create a nice UI. If someone want's to create something similar UEZ was kind enough to share his code of creating such GUI with nice antialiased labels. 
      https://www.autoitscript.com/forum/topic/178366-adobe-air-like-window/#comment-1280587

    • water
      By water
      I just noticed that Trac ticket #2108 was closed as "No bug".
      I understand that the code as it is now might already be broken because it does more than originally intended.
      On the other hand the change smartee proposed solved my problem (described ). I implemented and tested smartees code and it now allows to sequentially run compiled scripts an application I can't control starts in a bunch.

      I think every code change that enhances the functionality of AutoIt should be welcome. In particular when its jut 2 lines of code and the risk of side effects is minimal.
      I vote for implementing smartees change.
      Just my 2 cents.