why is second thread not working? def add(thread): path =…
- User
why is second thread not working?
def add(thread): path = r"C:\Users\Plathera\Desktop\4224.json" index = 0 while True: try: print(f"\nthread: {thread}") index+=1 with open (path, encoding='utf-8') as file: data = json.load(file) data.append(index) with open (path, 'w', encoding='utf-8') as file: json.dump(data, file)
time.sleep(0.1) print(data) except: Print('ERROR', 'red') # print(Load_Json(path))Create threads for each function
t1 = threading.Thread(target=add(1)) t2 = threading.Thread(target=add(2))
- Assistant
The issue with the provided code is primarily in how you're creating your threads with the
threading.Threadobjects. When you specifytarget=add(1)andtarget=add(2), you're actually calling theaddfunction immediately and attempting to pass its return value (which isNone, sinceadddoesn't return anything) as the target function for the thread. This results in theaddfunction being executed sequentially, not in parallel as intended, because you're not passing the function itself but the result of its execution to the thread.To fix this, you should pass the function object and the arguments separately using the
targetandargsparameters of thethreading.Threadconstructor. This way, you tell the Thread object to call this function with these arguments when it starts. Here's how you should modify your code:import threading import json import time def add(thread): path = r"C:\Users\Plathera\Desktop\4224.json" index = 0 while True: try: print(f"\nthread: {thread}") index+=1 with open (path, encoding='utf-8') as file: data = json.load(file) data.append(index) with open (path, 'w', encoding='utf-8') as file: json.dump(data, file) time.sleep(0.1) print(data) except Exception as e: # Changed to print(str(e)) for demonstration purposes # Replace following line according to your error handling print(str(e)) # Create threads for each function t1 = threading.Thread(target=add, args=(1,)) # Notice the use of args to pass arguments t2 = threading.Thread(target=add, args=(2,)) # to your function. # Don't forget to start your threads! t1.start() t2.start() t1.join() # Optionally, wait for t1 to finish t2.join() # Optionally, wait for t2 to finishA few additional notes on your code:
- Make sure you have all the required imports (
import threading,import json,import time) at the top of your script. - In your
except:block, you havePrintwhich should be lowercase (print). Also, to enhance your error handling, consider catching a specific exception (or printing the exception message) rather than a general catch-all. This would help in debugging. - Using
time.sleep(0.1)for control in a multi-threaded environment interacting with the same file could lead to race conditions or data corruption. If two threads try to read and write to the file simultaneously, you might end up with unexpected behavior. You might want to consider using locks (from thethreadingmodule) around your file reading/writing operations to ensure that only one thread can work with the file at a time, or rethinking your design if concurrent file access is a necessity.
- Make sure you have all the required imports (