需要简单的线程示例
考虑到以下要求,有人可以发布一个非常简单的代码示例,说明如何使用多线程,同时正确利用锁来保持共享数据的“安全”?
假设您将整数 x 声明为 100。然后,您想要生成 10 个线程,每个线程执行一些操作。当每个线程完成操作时,它会递减 x。我知道您可以为此使用互锁,但是在评估条件时您是否也需要锁?换句话说,在执行操作之前,您需要确保 x 大于 0。
Given the following requirements, could someone post a very simple code sample illustrating how you could use multi-threading, and at the same time properly utilize locks to keep the shared data "safe"?
Say you declare an integer x to be 100. Then, you want to spawn off 10 threads to each perform some action. As each thread completes the action, it decrements x. I know you can use interlocked for this, but wouldn't you also need a lock when you evaluate the condition? In other words, you need to make sure that x is greater than 0 before you perform the action.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
lock
关键字包装对x
的每次访问:这将确保对 x 的所有访问都是原子的,并且不存在与线程安全相关的危险。
You can wrap every access to
x
with thelock
keyword:This will ensure that all accesses to x are atomic, and there is no danger related to thread-safety.
如果您想编写简单的多线程程序,请考虑使用 C# 4.0 中的并行扩展。
具有锁和可变共享数据的普通多线程程序绝不简单。
If you want to write simple multithreaded programs, consider using the parallel extensions in C# 4.0.
Plain multithreaded programs with locks and mutable shared data are never simple.
您可能不想在操作完成后递减计数器,因为计数器可能为 1,所有 10 个线程都会检查它,发现它大于零,然后开始执行操作,只有在完成时才将其递减。
您可以使用 Interlocked.Decrement 来减少计数器并在之前检查其值在不锁定的情况下执行操作:
You probably don't want to decrement the counter after the operation has finished, as the counter could be 1, all 10 threads would check it, see that it's greater than zero, and start performing the action, only to all decrement it on completion.
You can use Interlocked.Decrement to decrement the counter and check its value before performing the action without locking:
您想要使用Interlocked.CompareExchange。假设您要修改一个名为
Counter
的共享变量。如果您希望线程在退出之前处理最多 10 个项目,则可以将其包装在循环中。
请注意,计数器控制处理方法的进入。也就是说,从逻辑上讲,它的工作原理如下:
您的问题似乎要求类似以下内容:
但如果您以这种方式编码,那么您可能会调用
DoAction
超过 100 次(或任何初始值)counter
是),因为其他线程可以在最后一个线程完成之前开始该操作。You want to use Interlocked.CompareExchange. Let's say you want to modify a shared variable called
Counter
.You can wrap that in a loop if you want your thread to process up to 10 items before it exits.
Note that the counter controls entry to the processing method. That is, logically it works like this:
Your question seems to ask for something like:
But if you code it that way, then you'll likely call
DoAction
more than 100 times (or whatever the initial value ofcounter
is) because other threads can start the action before the last one is done.如果你想做你自己的事情,只需实现你自己的逻辑
If you want to do your version of things just implement your own logic