Last active
August 29, 2015 14:10
-
-
Save python012/21317c81469326bd3100 to your computer and use it in GitHub Desktop.
Practice multiple threads code, will improve one of my Python programs' efficiency.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
''' | |
Created on 2014年12月7日 | |
@author: reed | |
''' | |
import thread | |
import time | |
count = 0 | |
lock = thread.allocate_lock() | |
def threadTest(): | |
global count | |
for i in xrange(100000): | |
global lock | |
lock.acquire() | |
count += 1 | |
lock.release() | |
for i in range(6): | |
thread.start_new_thread(threadTest, ()) | |
time_to_wait = 10 # This time need be long enough, otherwise CPU may not finish processing | |
# the counting task when it run to "print count". | |
for x in range(time_to_wait): | |
print time_to_wait - x | |
time.sleep(1) | |
print count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually I still have question on lock.acquire() and lock.release(), shall I put it out of the for loop?