一个python多进程计数器的问题
巴扎黑
巴扎黑 2017-04-18 10:33:29
0
1
732

写了个多进程的脚本,然后其中有个计数器,大致逻辑如下

def worker(co):
    # working
    co[0] += 1
    if co[0] % 10000 == 0:
        logging.info("Parsed {}".format(co[0]))
        
def main():
    co = Manager.list()
    co[0] = 1
    pool = Pool()
    for i in range(10):
        pool.apply_async(worker, (co,))

最终程序运行时发现个有趣的问题

INFO: 2017-04-11 16:42:19,288 - 13582 - Parsed 879999
INFO: 2017-04-11 16:42:19,292 - 13583 - Parsed 880000
INFO: 2017-04-11 16:42:19,295 - 13593 - Parsed 880001
INFO: 2017-04-11 16:42:19,297 - 13597 - Parsed 880001

这里的880001,多一个我能理解,当if co[0] % 10000 == 0判断时,其他进程已经做了加一操作了,但这个879999少一个,我就有点想不通了?

巴扎黑
巴扎黑

reply all(1)
洪涛

The process that meets the printing conditions is just about to print, and other processes are doing the +1 operation, getting the value, +1, and assigning the value back requires several instructions. In fact, any value may appear, because the instruction to get the value can occur at any time.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!