免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: pigvip
打印 上一主题 下一主题

threadpool怎么读写全局变量? [复制链接]

论坛徽章:
0
11 [报告]
发表于 2008-05-05 11:29 |只看该作者
下面是输出,对不对?
nihao
nihao
8.34617
**Result: 8.34617 from request #57364272
0.88989
**Result: 0.88989 from request #57301352
9.23606

论坛徽章:
0
12 [报告]
发表于 2008-05-05 11:41 |只看该作者
不是所有的都运行正常的,线程多了就会有报错。你多试几次就会出现报错了,可能是线程冲突,估计的有线程锁才可以。

论坛徽章:
0
13 [报告]
发表于 2008-05-05 15:19 |只看该作者
那个库没有同步机制?那还不如自己写算了

论坛徽章:
4
CU大牛徽章
日期:2013-03-13 15:29:07CU大牛徽章
日期:2013-03-13 15:29:49CU大牛徽章
日期:2013-03-13 15:30:192015亚冠之广州恒大
日期:2015-07-22 17:20:15
14 [报告]
发表于 2008-05-17 14:08 |只看该作者
全局变量 加锁

论坛徽章:
0
15 [报告]
发表于 2008-05-21 10:20 |只看该作者
原帖由 ghostwwl 于 2008-5-17 14:08 发表
全局变量 加锁


我是过全局变量 加锁了仍然不行,后来看了这个线程池的代码里面是把运行方法的结果保存到一个队列里,我直接写个类试属性的方法,等线程执行完,取这个队列的数据就可以了。

论坛徽章:
0
16 [报告]
发表于 2008-05-21 13:44 |只看该作者
Queue就是线程安全的,不想加锁就用这个好了。
另外,为什么全局变量加锁不行呢?不可能的,你在哪加的?怎么加的?

论坛徽章:
0
17 [报告]
发表于 2008-05-21 14:25 |只看该作者
if __name__ == '__main__':
    import random
    import time

    res = []
    global_locker=threading.Lock()

    # the work the threads will have to do (rather trivial in our example)
    def do_something(data):
        time.sleep(random.randint(1,5))
        result = round(random.random() * data, 5)
        print(result)
        # just to show off, we throw an exception once in a while
        #if result > 3:
            #raise RuntimeError("Something extraordinary happened!")
        return result

    # this will be called each time a result is available
    def print_result(request, result):
        global res
        global_locker.acquire()
        res.append(result)

        print "**Result: %s from request #%s" % (result, request.requestID)
        global_locker.release()
        
    # this will be called when an exception occurs within a thread
    def handle_exception(request, exc_info):
        print "Exception occured in request #%s: %s" % \
          (request.requestID, exc_info[1])

    # assemble the arguments for each job to a list...
    data = [random.randint(1,10) for i in range(100)]

    # ... and build a WorkRequest object for each item in data
    requests = makeRequests(do_something, data, print_result, handle_exception,)

    # or the other form of args_lists accepted by makeRequests: ((,), {})
    """
    data = [((random.randint(1,10),), {}) for i in range(20)]
    requests.extend(
      makeRequests(do_something, data, print_result, handle_exception)
    )
    """
    # we create a pool of 3 worker threads
    main = ThreadPool(10)
    #global res
    #res=''
    # then we put the work requests in the queue...
    for req in requests:
        main.putRequest(req)
        #print "Work request #%s added." % req.requestID
        sfd=str(req.callable)
        if sfd.find('do_something') > 0:
            print "nihao"
    # or shorter:
    # [main.putRequest(req) for req in requests]

    # ...and wait for the results to arrive in the result queue
    # by using ThreadPool.wait(). This would block until results for
    # all work requests have arrived:
    # main.wait()

    # instead we can poll for results while doing something else:
    main.wait()
    print(res)
    print len(res)
    """
    i = 0
    while 1:
        try:
            main.poll()
            print "Main thread working..."
            time.sleep(0.5)
            if i == 10:
                print "Adding 3 more worker threads..."
                main.createWorkers(3)
            i += 1
        except KeyboardInterrupt:
            print "Interrupted!"
            break
        except NoResultsPending:
            print "All results collected."
            break
    """

修改的地方是红的,没太仔细看,有问题再告诉我吧
100条数据,10个线程执行,数据是随机出现的,我也就没仔细查,最后看结果的数目还是对的。

论坛徽章:
0
18 [报告]
发表于 2008-05-21 14:27 |只看该作者
全局变量加锁应该可以。

论坛徽章:
0
19 [报告]
发表于 2008-05-22 16:34 |只看该作者
原帖由 chrisyan 于 2008-5-21 14:25 发表
if __name__ == '__main__':
    import random
    import time

    res = []
    global_locker=threading.Lock()
    # the work the threads will have to do (rather trivial in our example)
    ...

我记我加的和这个类试,但红色这块不太一样。提示的意思可能是没有复值就使用。  
        global res
        global_locker.acquire()
        res=res+result
        print "**Result: %s from request #%s" % (result, request.requestID)
        global_locker.release()

另外我没在外面使用这个res = []。可能问题在这吧?

[ 本帖最后由 pigvip 于 2008-5-22 16:36 编辑 ]

论坛徽章:
0
20 [报告]
发表于 2008-05-23 21:23 |只看该作者
好久没看书了,生疏了。我不太记得可不可以直接在一个子代码块上直接声明一个global变量,手头上也没有python解释器来试。
但是我觉得你写global res的时候要不要赋值呢?不然这个变量是什么类型的呢?python可是强类型的哦。我只是让res是一个空list,所以我在后面用list的append方法吧内容放进list里.如果你定义res是str的话,那你就可以写res+=result串起来。
你所说的问题是和锁无关的,建议你先补补python了,我也要补补了,老本吃光了,呵呵
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP