Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

why is second thread not working? def add(thread): path =…

  1. 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))

  2. Assistant

    The issue with the provided code is primarily in how you're creating your threads with the threading.Thread objects. When you specify target=add(1) and target=add(2), you're actually calling the add function immediately and attempting to pass its return value (which is None, since add doesn't return anything) as the target function for the thread. This results in the add function 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 target and args parameters of the threading.Thread constructor. 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 finish
    

    A 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 have Print which 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 the threading module) 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.