import threading
import time
counter = 0
def increase(name):
global counter
i = 0
while i < 30:
for x in xrange(100000):
1+1
counter += 1
print name + " " + str(counter)
i += 1
if __name__ == '__main__':
threads = []
try:
for i in xrange(100):
name = "Thread-" + str(i)
t = threading.Thread( target=increase, args=(name,) )
t.start()
threads.append(t)
except:
print "Error: unable to start thread"
for t in threads:
t.join()
Python version is 2.7.5.
In the above code, I run it several times, the final result is always 3000.
And this code is also an example of this blog.
http://effbot.org/zone/thread-synchronization.htm
But this blog also mentions that:
In general, this approach only works if the shared resource consists of one instance of the main data type, such as a string variable, number, list, or dictionary. Here are some thread safe operations:
- reading or replacing a single instance attribute
- reading or replacing one global variable
- select an item from a list
- change the list in place (for example, adding an item by adding)
- select an item from a dictionary
- (, clear)
, , python?
1
Linux- CentOS Linux release 7.2.1511, 3.10.0-123.el7.x86_64 #1 SMP Mon Jun 30 12:09:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux.
mac - 10.11.5 (15F34), python - 2.7.10.
Mac, , , - .
Linux, .
counter:3000, expected:3000
counter:3000, expected:3000
counter:3000, expected:3000
counter:3000, expected:3000
counter:3000, expected:3000
- , ?
2
, ββLinux, , . linux-, 4 , .
Python GIL, , , , . GIL ?
, ?
.