需要简单的线程示例

发布于 2024-10-23 21:32:48 字数 189 浏览 1 评论 0原文

考虑到以下要求,有人可以发布一个非常简单的代码示例,说明如何使用多线程,同时正确利用锁来保持共享数据的“安全”?

假设您将整数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

放赐 2024-10-30 21:32:48

您可以使用 lock 关键字包装对 x 的每次访问:

private object xLock = new object();

...

lock (xLock)
{
   // Any read or write access to x
}

这将确保对 x 的所有访问都是原子的,并且不存在与线程安全相关的危险。

You can wrap every access to x with the lock keyword:

private object xLock = new object();

...

lock (xLock)
{
   // Any read or write access to x
}

This will ensure that all accesses to x are atomic, and there is no danger related to thread-safety.

一抹微笑 2024-10-30 21:32:48

如果您想编写简单的多线程程序,请考虑使用 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.

东京女 2024-10-30 21:32:48

您可能不想在操作完成后递减计数器,因为计数器可能为 1,所有 10 个线程都会检查它,发现它大于零,然后开始执行操作,只有在完成时才将其递减。

您可以使用 Interlocked.Decrement 来减少计数器并在之前检查其值在不锁定的情况下执行操作:

int temp = Interlocked.Decrement(x);

if(temp >= 0) //temp is the decremented value
{
    //perform action
}

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:

int temp = Interlocked.Decrement(x);

if(temp >= 0) //temp is the decremented value
{
    //perform action
}
━╋う一瞬間旳綻放 2024-10-30 21:32:48

您想要使用Interlocked.CompareExchange。假设您要修改一个名为 Counter 的共享变量。

int count = Counter;
if (count == 0)
    return;
if (Interlocked.CompareExchange(ref Counter, count-1, count) == count)
{
    // Counter was decremented.
    // perform your processing.
}

如果您希望线程在退出之前处理最多 10 个项目,则可以将其包装在循环中。

请注意,计数器控制处理方法的进入。也就是说,从逻辑上讲,它的工作原理如下:

if (counter > 0)
{
    --counter;
    DoAction();
}

您的问题似乎要求类似以下内容:

if (counter > 0)
{
    DoAction();
    --counter;
}

但如果您以这种方式编码,那么您可能会调用 DoAction 超过 100 次(或任何初始值) counter 是),因为其他线程可以在最后一个线程完成之前开始该操作。

You want to use Interlocked.CompareExchange. Let's say you want to modify a shared variable called Counter.

int count = Counter;
if (count == 0)
    return;
if (Interlocked.CompareExchange(ref Counter, count-1, count) == count)
{
    // Counter was decremented.
    // perform your processing.
}

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:

if (counter > 0)
{
    --counter;
    DoAction();
}

Your question seems to ask for something like:

if (counter > 0)
{
    DoAction();
    --counter;
}

But if you code it that way, then you'll likely call DoAction more than 100 times (or whatever the initial value of counter is) because other threads can start the action before the last one is done.

以歌曲疗慰 2024-10-30 21:32:48

如果你想做你自己的事情,只需实现你自己的逻辑

lock(somecommonreference)
{
   if (x>0) x--;
}

If you want to do your version of things just implement your own logic

lock(somecommonreference)
{
   if (x>0) x--;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文