threading problems

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gabitzu4224
    New Member
    • Jan 2008
    • 3

    threading problems

    main problem is i dont really understand threads, and at the moment they are my only option because im working on windows and it doesnt support fork processes.ran this program and all i got was a random integer ( 348 )

    import thread

    mutex=thread.al locate_lock()
    f=open('newText .txt.','w')

    def counter2(ID):
    mutex.acquire()
    f.write(ID,'\nN umbers are ')
    for i in range(5): f.write(i)
    f.write('\n')
    mutex.release()


    thread.start_ne w(counter2,(1,) )



    ...and and all i got was an integer which wasnt even supposed to appear (i understand that each thread when started they return a value which is supposed to be ignored), the file cointains nothing
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by gabitzu4224
    main problem is i dont really understand threads, and at the moment they are my only option because im working on windows and it doesnt support fork processes.ran this program and all i got was a random integer ( 348 )

    import thread

    mutex=thread.al locate_lock()
    f=open('newText .txt.','w')

    def counter2(ID):
    mutex.acquire()
    f.write(ID,'\nN umbers are ')
    for i in range(5): f.write(i)
    f.write('\n')
    mutex.release()


    thread.start_ne w(counter2,(1,) )



    ...and and all i got was an integer which wasnt even supposed to appear (i understand that each thread when started they return a value which is supposed to be ignored), the file cointains nothing
    First of all please us code tags.

    In your counter2 function there are a couple errors. Why are you passing 2 arguements to f.write()? Why are you passing an integer to f.write()? You should only pass a single string to that function.

    Also, you shouldn't exit the main thread until all your chil threads have exited. You could do something like this:
    [code=python]
    import thread
    import time

    mutex=thread.al locate_lock()
    f=open('newText .txt.','w')
    done = false

    def counter2(ID):
    mutex.acquire()
    f.write(ID,'\nN umbers are ')
    for i in range(5):
    f.write(i)
    f.write('\n')
    mutex.release()
    done = true


    thread.start_ne w(counter2,(1,) )

    while not done:
    time.sleep(0.2)
    [/code]
    That might not be necessary though depending on what you are doing.

    Comment

    Working...