Friday, September 11, 2015

Python: Multithreading(1) thread module

Abstract: The module known as thread used for multiple threads running

The process of running the below script accidentally results in errors:
The correct result:
in: 1
in: 2
in: 3
in: ID:2, input:2
ID:1, input:1
ID:3, input:3
ID:4, input:4
ok

Some wrong results:
in: 1
in: 2
in: 3
in: 4
 ok
ID:4=4

or with some errors:
Unhandled exception in thread started by <function loop at 0x7f4b677806e0>
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/abrt_exception_handler.py", line 288, in <lambda>
    sys.excepthook = lambda etype, value, tb: handleMyException((etype, value, tb))
ID:4=4
TypeError:

The script:
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 10:13:24 2015

@author: yuan
"""

import thread
import time

#
def loop(tid,x):
    print 'ID:%s=%s\n' % (tid,x)
    time.sleep(100000)

#endless loop
def eloop(tid,x):
    print 'ID:%s, input:%s\n' % (tid,x)
    time.sleep(10)
    while True:
        x=x^1
       
#multi-threading
def multithreading():
    for i in range(1,5):
        print 'in:', i
        thread.start_new_thread(loop, (i,i))
        #if raw_input()=='q':
        #   break


if __name__=="__main__":
    multithreading()
    print 'ok'

No comments:

Post a Comment