Python Forum
help with threading module and passing global variables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with threading module and passing global variables
#1
Hi

I'm having a big trouble to get this to work.

I have a function that I want to put in a thread (or multiprocess). This function requires 3 variables.
One of the variables (var_1) is static and no problem passing it through args in the thread module.
The second variable (var_2) changes during the main program

The last variable (flag) i want to use as a trigger when it gets True in the main program.


The "mental" structure of the program should be:

main.py

import threading
from test import function
import time

global flag, var_2

var_1 = "var_1"

t = threading.Thread(target=function, args=(var_1,))
t.start()

while True:
    var_2 = "var_2 (that changes in each while loop"
    flag = True
    time.sleep(1)
    flag = False
test.py

def function(var_1):
    global var_2, flag
    while True:

        if flag == True:
            print(var_1 + var_2)
But this does not work i think

Someone guru could help me?
Reply
#2
First, as a maxim, don't use globals. They're more trouble than they're worth.

Second, you need a thread safe data structure to conduct this operation. "Thread safe" means that the variable can only be accessed by one thread at a time which ensures consistency when any thread uses it. Without thread safety, there may be the possibility of thread1 evaluating the variable, thread 2 changes it, and then thread 1 runs a calculation with the changed variable and gets a nonsensical result. Read up on multithreading locks. Once a lock is implemented, the function will need the variable as an argument.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  importing variables from module 8376459 1 245 Feb-18-2024, 02:24 PM
Last Post: deanhystad
  Trying to understand global variables 357mag 5 1,064 May-12-2023, 04:16 PM
Last Post: deanhystad
  Concurrent futures threading running at same speed as non-threading billykid999 13 1,715 May-03-2023, 08:22 AM
Last Post: billykid999
  Why Pip is not listed in the official Global Python Module index? quazirfan 2 731 Apr-21-2023, 10:55 AM
Last Post: snippsat
  Global variables or local accessible caslor 4 984 Jan-27-2023, 05:32 PM
Last Post: caslor
  global variables HeinKurz 3 1,100 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  Clarity on global variables JonWayn 2 904 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Tutorials on sockets, threading and multi-threading? muzikman 2 2,076 Oct-01-2021, 08:32 PM
Last Post: muzikman
  Global variables not working hobbyist 9 4,615 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,595 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020