Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Did the threading module change in Python 3? And if so, how?

$
0
0

I'm trying to understand the MT in Python. I found an example using threading.Lock. But it generated different outputs in Python 2.7 and Python 3.6, which really confused me.

Here is the code:

import threadingimport timeimport random class meThread(threading.Thread):    def run(self):       global num       time.sleep(random.randint(1,3))       num += 1       print(self.name+'set num to '+str(num)) num = 0 threads = [] for i in range(5):    t = meThread()    threads.append(t) for i in range(5):    threads[i].start() for i in range(5):    threads[i].join()

and the output in Python3.6:

Thread-4set num to 1Thread-2set num to 2Thread-1set num to 3Thread-3set num to 4Thread-5set num to 5

and the output in Python2.7:

Thread-1set num to 1Thread-4set num to 2Thread-3set num to 4Thread-2set num to 5Thread-5set num to 3

The output is always the same in 3.6, but in 2.7 it's unexpected if not using threading.Lock. Why? Does the python add a lock to a thread automatically in 3.6?


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>