问题:压力测试memcached,写多线程set和get数据,类的静态变量,好吧c++才这么称呼,python叫做类属性,做了个简单的计数器,但统计一直不对。想来是没有加锁的问题,测试了一下通过了,就是没有加互斥锁,谢谢吞文提醒,互斥锁和多核没什么必然关系,多线程的竞争资源不加锁处理一定会有问题的。下面是个简单的例子,python中的加锁方式:
=================================================
#--*-- coding=utf8 --*--
import thread
import time
dish=0
lock = thread.allocate_lock()
class testthread():
xt=0
global lock,dish
def threadFunction(self,count):
for i in range(count):
print('进程id为%d的打印%d'%(thread.get_ident(),i))
i-=1
#time.sleep(0.1)
if lock.acquire(2):
testthread.xt=testthread.xt+1
lock.release()
time.sleep(1)
def begin():
for x in range(50):
tx=testthread()
ident1=thread.start_new_thread(tx.threadFunction,(10,))
print('%d:stat为%d的进程'%(x,ident1,))
print "all process is ok"
if __name__ == '__main__':
begin()
while 1:
print "~~~~xt=%d" % testthread.xt
#time.sleep(1)
--------------------------------
#创建锁 mutex = threading.Lock() #锁定 mutex.acquire([timeout]) #释放 mutex.release()参考:http://www.cnblogs.com/holbrook/archive/2012/03/04/2378947.html
=================================================
#--*-- coding=utf8 --*--
import thread
import time
dish=0
lock = thread.allocate_lock()
class testthread():
xt=0
global lock,dish
def threadFunction(self,count):
for i in range(count):
print('进程id为%d的打印%d'%(thread.get_ident(),i))
i-=1
#time.sleep(0.1)
if lock.acquire(2):
testthread.xt=testthread.xt+1
lock.release()
time.sleep(1)
def begin():
for x in range(50):
tx=testthread()
ident1=thread.start_new_thread(tx.threadFunction,(10,))
print('%d:stat为%d的进程'%(x,ident1,))
print "all process is ok"
if __name__ == '__main__':
begin()
while 1:
print "~~~~xt=%d" % testthread.xt
#time.sleep(1)
--------------------------------
没有评论:
发表评论