Understanding Value Binding Within CFThread

Posted November 9, 2007 at 7:50 AM by Ben Nadel

Tags: ColdFusion

Yesterday, Bjorn Jensen brought a very interesting ColdFusion 8 CFThread problem to my attention. He was launching threads within a CFLoop and then using the loop index value within the code of each individual thread. What he was seeing was that the value of the index variable seemed to be completely unpredictable. If you are not used to programming in an asynchronous environment (and I think most ColdFusion developers are not), this is complete confusing. The only reason I had any idea what was going on was because I do a lot of programmatic event binding in Javascript and similar problems crop up.

The real problem here is understanding when a variable value is actually being evaluated. For the code within a CFThread, variables are evaluated ONLY at the time that the variable-referencing line is executed, not when it is defined. In typical procedural programming, these events are generally one and the same; however, in a multi-threading environment with thread queuing, a variable's usage might be defined at one point and then not executed until a later time.

This is what was causing Bjorn's problem. His CFLoop was starting and completing before ColdFusion 8 executed all of the threads. This means that for any of the threads that were lower in the thread queue, by the time their code was executed, the CFLoop index value held a value that was one greater than the TO attribute of the CFLoop tag. And, since the variable value is evaluated only at variable execution time, many of the threads referenced the same value.

To demonstrate this issue, I have put together a demo in which we create threads that reference a VARIABLES-scoped value:

  • <!--- Launch 20 threads. --->
  • <cfloop
  • index="intIndex"
  • from="1"
  • to="20"
  • step="1">
  •  
  •  
  • <!--- Launch ASYNCHRONOUS thread. --->
  • <cfthread
  • action="run"
  • name="thread#intIndex#">
  •  
  • <!---
  • Randomly sleep a thread. This will ensure that the
  • index value is not firing instantly.
  • --->
  • <cfif RandRange( 0, 1 )>
  •  
  • <!--- Sleep thread for half second. --->
  • <cfthread
  • action="sleep"
  • duration="#(1 * 500)#"
  • />
  •  
  • </cfif>
  •  
  • <!---
  • Store the variable in the THREAD scope. This will
  • bind the value of the index variable to the pass-
  • by-value count.
  • --->
  • <cfset THREAD.IndexValue = intIndex />
  •  
  • </cfthread>
  •  
  • </cfloop>
  •  
  •  
  • <!--- Wait for all the threads to join the current page. --->
  • <cfthread
  • action="join"
  • />
  •  
  •  
  • <!---
  • Loop over all the threads and output the index value
  • that was bound to the thread-scoped variable.
  • --->
  • <cfloop
  • index="intIndex"
  • from="1"
  • to="20"
  • step="1">
  •  
  • Thread #intIndex# :
  •  
  • #CFTHREAD[ "thread#intIndex#" ].IndexValue#<br />
  •  
  • </cfloop>

In the code, we are randomly sleeping some of the threads to simulate an environment in which threads may not execute in the same order in which they were defined. Running the above code, we get the following output:

Thread 1 : 2
Thread 2 : 3
Thread 3 : 21
Thread 4 : 21
Thread 5 : 6
Thread 6 : 21
Thread 7 : 21
Thread 8 : 21
Thread 9 : 21
Thread 10 : 21
Thread 11 : 21
Thread 12 : 13
Thread 13 : 14
Thread 14 : 21
Thread 15 : 16
Thread 16 : 17
Thread 17 : 21
Thread 18 : 21
Thread 19 : 21
Thread 20 : 21

Notice that the majority of threads stored the value, 21, which was the index value after the loop finished executing.

To get around this, you should avoid referring to variables outside of the currently executing thread. In the above case, we were referring the CFLoop index variable which was defined outside of the currently executing thread. Instead of referring to the VARIABLES-scoped value, we should pass the value into the thread using ColdFusion 8's CFThread custom tag attributes:

  • <!--- Launch 20 threads. --->
  • <cfloop
  • index="intIndex"
  • from="1"
  • to="20"
  • step="1">
  •  
  •  
  • <!---
  • Launch ASYNCHRONOUS thread, but this time, pass the
  • index value into the thread using a custom attribute.
  • This will get the variable value to evalute a the
  • time the thread is defined.
  • --->
  • <cfthread
  • action="run"
  • name="thread#intIndex#"
  • indexvalue="#intIndex#">
  •  
  • <!---
  • Randomly sleep a thread. This will ensure that the
  • index value is not firing instantly.
  • --->
  • <cfif RandRange( 0, 1 )>
  •  
  • <!--- Sleep thread for half second. --->
  • <cfthread
  • action="sleep"
  • duration="#(1 * 500)#"
  • />
  •  
  • </cfif>
  •  
  • <!---
  • Store the variable in the THREAD scope. This time,
  • refer to the ATTRIBUTES scope rather than the
  • VARIABLES scope since the variable was passed into
  • the CFThread tag at the time of thread definition.
  • --->
  • <cfset THREAD.IndexValue = ATTRIBUTES.IndexValue />
  •  
  • </cfthread>
  •  
  • </cfloop>
  •  
  •  
  • <!--- Wait for all the threads to join the current page. --->
  • <cfthread
  • action="join"
  • />
  •  
  •  
  • <!---
  • Loop over all the threads and output the index value
  • that was bound to the thread-scoped variable.
  • --->
  • <cfloop
  • index="intIndex"
  • from="1"
  • to="20"
  • step="1">
  •  
  • Thread #intIndex# :
  •  
  • #CFTHREAD[ "thread#intIndex#" ].IndexValue#<br />
  •  
  • </cfloop>

Notice here that we are passing the variable in using ColdFusion 8's custom CFThread tag attributes. This loads that value into the thread's ATTRIBUTES scope. But, more importantly, it's forcing ColdFusion to evaluate the variable at the moment that the individual threads are defined. Running the above code, we get the following output:

Thread 1 : 1
Thread 2 : 2
Thread 3 : 3
Thread 4 : 4
Thread 5 : 5
Thread 6 : 6
Thread 7 : 7
Thread 8 : 8
Thread 9 : 9
Thread 10 : 10
Thread 11 : 11
Thread 12 : 12
Thread 13 : 13
Thread 14 : 14
Thread 15 : 15
Thread 16 : 16
Thread 17 : 17
Thread 18 : 18
Thread 19 : 19
Thread 20 : 20

This time, it works just as expected. So remember, try to pass variables into a CFThread tag if you are going to refer to them within the tag execution.




Reader Comments

Nov 9, 2007 at 9:38 AM // reply »
5 Comments

Nice writeup, Ben.


Nov 9, 2007 at 9:51 AM // reply »
10,640 Comments

@Jeff,

Thanks. I think CFThread is a big shift in mentality for a lot of people, so it's really important to explore this type of thing. It's double important since you can't really output the screen from within an asynchronous thread. But this stuff is really cool.


Mar 24, 2010 at 7:27 PM // reply »
6 Comments

Thanks Ben, I knew you would have some reference to this :)


Mar 24, 2010 at 10:23 PM // reply »
10,640 Comments

@DeepDown,

No problem my man; as a rule of thumb, I typically pass all my thread-based variables as part of the CFThread tag attributes. You just have to be careful when you are dealing with what are typically pass-by-reference values since CFThread attributes are passed-by-VALUE across the board (including structs and CFCs).


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 12, 2012 at 3:37 AM
Learning ColdFusion 8: CFImage Part III - Watermarks And Transparency
Hi Ben, Just to ask currently it is placed bottom right corner, if i need to replace the same rendered image on the bottom left side or in the bottom center, how that can be calculated. bottom ce ... read »
Feb 11, 2012 at 9:29 PM
Use jQuery's SlideDown() With Fixed-Width Elements To Prevent Jumping
I can't say how glad I am that I found your post. Thank you very much. ... read »
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »