Oxygen Basic

Information => Development => Topic started by: Brian Alvarez on May 07, 2019, 10:09:53 PM

Title: Thread-local variables.
Post by: Brian Alvarez on May 07, 2019, 10:09:53 PM

Charles, is there currently a way to implement thread-local variables?

 I mean, variables that are global to each module, and function and class method, but are independent for each different thread? (GLOBAL variables are shared across threads)
Title: Re: Thread-local variables.
Post by: Charles Pegge on May 08, 2019, 01:17:03 PM
o2 does not support thread_local variables but you could create thread objects quite easily, then the object members would have similar scope to thread_local, with additional advantages.
Title: Re: Thread-local variables.
Post by: Brian Alvarez on May 08, 2019, 10:42:47 PM
Thanks! Can you show me an example Charles?
Title: Re: Thread-local variables.
Post by: Charles Pegge on May 09, 2019, 02:19:39 AM

This demo increments a counter in a thread, which can be monitored from the console.

Code: [Select]
uses corewin
uses console
extern
'
class ThreadDemo
================
int counter
int running
sys thread
'
function constructor()
  counter=0
  running=1
  thread=CreateThread(0,0,@threadcall,@this,0,0)
end function
'
function destructor()
  CloseHandle(thread)
end function
'
function threadcall()
  while running
    act()
  wend
end function
'
function act()
  counter++
  sleep 20
end function
'
function stop()
  running=0
end function
'
end class
'
'TEST:
new ThreadDemo td()
int k
printl "Press [space] to show count, [enter] to close"
do
  k=waitkey
  select k
  case 3,13 : td.stop() : exit do
  case 32 : printl td.counter
  end select
loop
printl "Final count " td.counter
waitkey
del td
Title: Re: Thread-local variables.
Post by: Brian Alvarez on May 09, 2019, 11:59:56 AM
 In order to implement it, i would have to make every sub and function a method of a global class... kind of like java.

 I think i will have to create my own variables, and manage memory adresses manually.... No biggie, i just wanted to know if this
was already possible, if not, i will do it today.
Title: Re: Thread-local variables.
Post by: Charles Pegge on May 09, 2019, 08:50:24 PM
Yes. I agree. o2 has no core thread constructs. But OOP seems to be a perfect fit for clean threading.
Title: Re: Thread-local variables.
Post by: Brian Alvarez on May 09, 2019, 09:10:40 PM
 It already has under PluriBASIC. And they work absolutely fantastic.  ;D
Title: Re: Thread-local variables.
Post by: Brian Alvarez on May 09, 2019, 10:30:15 PM

Charles, i just noticed RND started misbehaving... i will post a new thread.