Author Topic: Thread-local variables.  (Read 1432 times)

0 Members and 2 Guests are viewing this topic.

Brian Alvarez

  • Guest
Thread-local variables.
« 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)

Charles Pegge

  • Guest
Re: Thread-local variables.
« Reply #1 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.
« Last Edit: May 08, 2019, 01:27:48 PM by Charles Pegge »

Brian Alvarez

  • Guest
Re: Thread-local variables.
« Reply #2 on: May 08, 2019, 10:42:47 PM »
Thanks! Can you show me an example Charles?

Charles Pegge

  • Guest
Re: Thread-local variables.
« Reply #3 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

Brian Alvarez

  • Guest
Re: Thread-local variables.
« Reply #4 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.
« Last Edit: May 09, 2019, 12:12:33 PM by Brian Alvarez »

Charles Pegge

  • Guest
Re: Thread-local variables.
« Reply #5 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.

Brian Alvarez

  • Guest
Re: Thread-local variables.
« Reply #6 on: May 09, 2019, 09:10:40 PM »
 It already has under PluriBASIC. And they work absolutely fantastic.  ;D
« Last Edit: May 09, 2019, 09:58:03 PM by Brian Alvarez »

Brian Alvarez

  • Guest
Re: Thread-local variables.
« Reply #7 on: May 09, 2019, 10:30:15 PM »

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