Cheat Engine Forum Index Cheat Engine
The Official Site of Cheat Engine
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 


Using critical sections

 
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Tutorials -> LUA Tutorials
View previous topic :: View next topic  
Author Message
Dark Byte
Site Admin
Reputation: 475

Joined: 09 May 2003
Posts: 25989
Location: The netherlands

PostPosted: Sun Aug 09, 2026 11:00 am    Post subject: Using critical sections Reply with quote

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
Back to top
View user's profile Send private message MSN Messenger
Display posts from previous:   
Post new topic   Reply to topic    Cheat Engine Forum Index -> Cheat Engine Tutorials -> LUA Tutorials All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You cannot download files in this forum


Powered by phpBB © 2001, 2005 phpBB Group

CE Wiki   IRC (#CEF)   Twitter
Third party websites