Skip to content

Instantly share code, notes, and snippets.

@python012
Last active August 29, 2015 14:10
Show Gist options
  • Save python012/21317c81469326bd3100 to your computer and use it in GitHub Desktop.
Save python012/21317c81469326bd3100 to your computer and use it in GitHub Desktop.
Practice multiple threads code, will improve one of my Python programs' efficiency.
#!/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
@python012
Copy link
Author

Actually I still have question on lock.acquire() and lock.release(), shall I put it out of the for loop?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment