Dark Byte Site Admin
Reputation: 475
Joined: 09 May 2003 Posts: 25989 Location: The netherlands
|
Posted: Sun Aug 09, 2026 11:00 am Post subject: Using critical sections |
|
|
Sometimes you'll need to use a critical section to prevent threading issues on some code that wasn't designed for multiple threads, like table.insert, table.remove, etc...
For those situations you can use a critical section (createCriticalSection/enter/leave) to prevent issues in the long run
I have an example script here. With a critical section the result will be 200, but if you where to run this without a critical section you'll end up with a list containing less than 200 entries, and some entries will have been overwritten by other threads
| Code: |
l={}
tl={}
tlcs=createCriticalSection() --replace with tlcs=nil so see the effect without
for i=1,200 do
s=createThreadSuspended(function() --spawn 200 threads in a suspended state
if tlcs then tlcs.enter() end
table.insert(l,i)
if tlcs then tlcs.leave() end
end)
table.insert(tl,s)
end
for i=1,#tl do --mark them all as do not free so we can wait for them to finish
tl[i].freeOnTerminate(false)
end
for i=1,#tl do
tl[i].resume() --start them all
end
for i=1,#tl do
tl[i].waitfor()
tl[i].destroy()
end
if tlcs then tlcs.destroy() tlcs=nil end
return #l --should be 200
|
_________________
Tools give you results. Knowledge gives you control.
Like my help? Join me on Patreon so i can keep helping |
|