Skip to main content
Known Participant
October 9, 2012
Question

Sometimes threading has a race condition on the last item.

  • October 9, 2012
  • 1 reply
  • 648 views

HI I am using the threading for the report i am doing,But some times having race condition on the last item.Below is the code for reference.

Some one please help me on this thanks...

<cfloop from="1" to="5" index="tid">

    <cfset threadlist = ListAppend(threadlist,"thread#tid#")>

    <cfthread action="run" name="thread#tid#"  dsn="#mydsn#">

        <cfloop condition="#ListLen(mylist)#">

            <cftry>

                <cflock name="remove_item" timeout="5">

                    <cfset id = ListGetAt( mylist, 1) />

                    <cfset mylist = ListDeleteAt(mylist, 1) />

                </cflock>

                <cftry>                   

                    <!--- doing some database stuff like updating table --->

                    <cfcatch type="Any">

                        <!--- error message  --->                       

                    </cfcatch>

                </cftry>

                <cfcatch type="any">                   

                        <!--- error message  --->  

                </cfcatch>

            </cftry>

        </cfloop>

       

    </cfthread>

</cfloop>

<cfthread action="join" name="#threadlist#" timeout="0" />

This topic has been closed for replies.

1 reply

BKBK
Community Expert
Community Expert
October 10, 2012

How do you know there is a race condition? In any case, you should tighten up your current code before testing it. Remove unnecessary details like dsn , id and cftry. Then you will get something like

<cfloop from="1" to="5" index="tid">

    <cfset threadlist = ListAppend(threadlist,"thread#tid#")>

    <cfthread action="run" name="thread#tid#">

        <cfloop condition="#ListLen(mylist)#">        

                <cflock name="remove_item" timeout="5">

                    <cfset mylist = ListDeleteAt(mylist, 1) />

                </cflock>                               

                <!--- doing some database stuff like updating table --->             

        </cfloop>

    </cfthread>

</cfloop>

<cfthread action="join" name="#threadlist#" timeout="0" />

You will see that, if listLen(mylist) is less than 5, say 3, then the last threads that run will not execute the lock. Could that explain what you've observed?