编写计数器程序python_Python多处理的简单方法实现简单的计数器?

Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done in total).

I looked up the API for Value, don't think it's mutable.

解决方案

Value is indeed mutable; you specify the datatype you want from the ctypes module and then it can be mutated. Here's a complete, working script that demonstrates this:

from time import sleep

from ctypes import c_int

from multiprocessing import Value, Lock, Process

counter = Value(c_int) # defaults to 0

counter_lock = Lock()

def increment():

with counter_lock:

counter.value += 1

def do_something():

print("I'm a separate process!")

increment()

Process(target=do_something).start()

sleep(1)

print counter.value # prints 1, because Value is shared and mutable

EDIT: Luper correctly points out in a comment below that Value values are locked by default. This is correct in the sense that even if an assignment consists of multiple operations (such as assigning a string which might be many characters) then this assignment is atomic. However, when incrementing a counter you'll still need an external lock as provided in my example, because incrementing loads the current value and then increments it and then assigns the result back to the Value.

So without an external lock, you might run into the following circumstance:

Process 1 reads (atomically) the current value of the counter, then increments it

before Process 1 can assign the incremented counter back to the Value, a context switch occurrs

Process 2 reads (atomically) the current (unincremented) value of the counter, increments it, and assigns the incremented result (atomically) back to Value

Process 1 assigns its incremented value (atomically), blowing away the increment performed by Process 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值