Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1102469
  • 博文数量: 170
  • 博客积分: 1603
  • 博客等级: 上尉
  • 技术积分: 1897
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-09 15:54
文章分类

全部博文(170)

文章存档

2016年(27)

2015年(21)

2014年(27)

2013年(21)

2012年(7)

2011年(67)

我的朋友

分类: Python/Ruby

2011-04-21 18:42:55


import time,datetime 
import threading 

def worker(a_tid,a_account): 
    global g_mutex 
    print "Str " , a_tid, datetime.datetime.now() 
    for i in range(1000000): 
        #g_mutex.acquire() 
        a_account.deposite(1) 
        #g_mutex.release() 
    print "End " , a_tid , datetime.datetime.now() 
     
class Account: 
    def __init__ (self, a_base ): 
        self.m_amount=a_base 
    def deposite(self,a_amount): 
        self.m_amount+=a_amount 
    def withdraw(self,a_amount): 
        self.m_amount-=a_amount     
         
if __name__ == "__main__": 
    global g_mutex 
    count = 0 
    dstart = datetime.datetime.now() 
    print "Main Thread Start At: " , dstart 

    #init thread_pool 
    thread_pool = [] 
    #init mutex 
    g_mutex = threading.Lock() 
    # init thread items 
    acc = Account(100) 
    for i in range(10): 
        th = threading.Thread(target=worker,args=(i,acc) ) ; 
        thread_pool.append(th) 
         
    # start threads one by one         
    for i in range(10): 
        thread_pool[i].start() 
     
    #collect all threads 
    for i in range(10): 
        threading.Thread.join(thread_pool[i]) 
    dend = datetime.datetime.now() 
    print "count=",acc.m_amount 
    print "Main Thread End at: " ,dend , " time span " , dend-dstart;


一开始我线程都是照着写的。后来发现sockect不能用join...因为有个永真循环,没有一个线程会结束。
重看这个脚本就能知道怎么写聊天室的群发了。
阅读(894) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~