首先,您start
的线程中的变量可以更改,因为它没有被传递。您在线程范围内需要的任何东西都应该在属性中传递。这使得变量线程安全。否则,如果变量在线程外发生变化,它也会在线程内发生变化,并可能产生意想不到的结果。THREAD
在线程内部,如果要在线程外部访问变量,可以将变量存储在范围内。您也可以将代码放入 try/catch 并将异常存储在THREAD
范围内,以便您可以在线程外部读取它以确定它是否出错以及为什么出错。
保留线程名称列表,然后<cfthread action="join">
在循环后使用。这告诉 CF 等到所有线程都完成。然后,您可以通过CFTHREAD
范围访问线程。该CFTHREAD
结构将使用线程名称的键存储您的线程,因此您可以循环遍历它。
<cfset start = CreateDate(2005, 1, 1) />
<cfset stop = DateAdd("m", 1, now() ) />
<cfset threadNames = ''>
<cfloop condition="start LTE stop">
<cfset newThreadName = dateformat(start, 'mmddyyyy') >
<!--- add thread name to list of threads --->
<cfset threadNames = listAppend(threadNames, newThreadName ) >
<cfthread name="#newThreadName#" action="run" start="#start#">
<cftry>
<!--- store a variable in THREAD scope to be used outside thread --->
<cfset THREAD.start = ATTRIBUTES.start>
<cfset THREAD.foo = "bar">
<!--- Do stuff here --->
<cfcatch type="any">
<!--- catch any error and store in the thread result --->
<cfset THREAD.exception = CFCATCH>
</cfcatch>
</cftry>
</cfthread>
<cfoutput> #LSDateFormat(start)# <br/> </cfoutput>
<cfset start = DateAdd("m", 1, start)>
</cfloop>
<!--- this waits for all threads to complete --->
<cfthread action="join" name="#threadNames#" />
<!--- loop over thread results --->
<cfloop collection="#CFTHREAD#" item="t">
<!--- do whatever you want with the thread result struct --->
<cfoutput>#CFTHREAD[t].STATUS# <br /></cfoutput>
</cfloop>
<!--- Dump all the threads --->
<cfdump var="#CFTHREAD#" abort="true" />