C# 多线程
好的。我想让两个线程运行。当前代码:
public void foo()
{
lock(this)
{
while (stopThreads == false)
{
foreach (var acc in myList)
{
// process some stuff
}
}
}
}
public void bar()
{
lock(this)
{
while (stopThreads == false)
{
foreach (var acc in myList)
{
// process some stuff
}
}
}
}
两者都访问同一个列表,问题是第一个线程“foo”没有释放我猜的锁;因为“bar”仅在“foo”完成后才开始。谢谢
Okay. I want to have two threads running. Current code:
public void foo()
{
lock(this)
{
while (stopThreads == false)
{
foreach (var acc in myList)
{
// process some stuff
}
}
}
}
public void bar()
{
lock(this)
{
while (stopThreads == false)
{
foreach (var acc in myList)
{
// process some stuff
}
}
}
}
Both are accessing the same List, the problem is that the first thread "foo" is not releasing the lock i guess; because "bar" only starts when "foo" is done. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这就是锁的设计原理。
互斥是指任一时刻最多只能有一个线程持有锁。
锁定这一点是一个坏主意,不鼓励这样做。您应该创建一个私有对象并锁定它。为了解决您的问题,您可以锁定两个不同的对象。
或者,您可以重复使用相同的锁,但将其移到循环内,以便每个循环都有机会继续进行:
但是,我建议您花一些时间来了解正在发生的事情,而不是重新排序代码行,直到它看起来可以工作在你的机器上。编写正确的多线程代码很困难。
为了停止线程,我推荐这篇文章:
Yes, that's how lock is designed to work.
Mutual-exclusion means that there can be at most one thread that holds the lock at any time.
Locking on this is a bad idea and is discouraged. You should create a private object and lock on that instead. To solve your problem you could lock on two different objects.
Alternatively you could reuse the same lock but move it inside the loop so that each loop has a chance to proceed:
However I would suggest that you spend some time to understand what is going on rather than reordering the lines of code until it appears to work on your machine. Writing correct multithreaded code is difficult.
For stopping a thread I would recommend this article:
由于您并不是真正在问问题,因此我建议您应该阅读有关线程如何工作的教程。可以此处找到 .Net 特定指南。它的主题包括“入门”、“基本同步”、“使用线程”、“高级线程”和“并行编程”。
另外,你还锁定了“这个”。 Msdn 说:
Since you are not really asking a question, I suggest you should read a tutorial on how threading works. A .Net specific guide can be found here. It features the topics "Getting Started", "Basic Synchronization", "Using Threads", "Advanced Threading" and "Parallel Programming".
Also, you are locking on "this". The Msdn says:
您遇到的问题是您使用的锁非常粗糙。 Foo 和 Bad 基本上不会同时工作,因为无论谁先启动,都会在整个工作周期中停止另一个。
不过,它应该仅在将内容从列表中删除时才锁定。根据定义,Foreach 在这里不起作用。您必须建立第二个列表,并让每个线程删除顶部的项目(同时锁定),然后对其进行处理。
基本上:
在你的情况下,你锁定的 foo 只会在 foo 完成时被释放。
The problem you have is that you work with a very coarse lock. Both Foo and Bad basically do not work concurrently because whoever starts first stops the other one for the COMPLETE WORK CYCLE.
It should, though, ONLY lock WHILE IT TAKES THINGS OUT OF THE LIST. Foreach does not work here - per definition. You ahve to put up a second list and have each thread REMOVE THE TOP ITEM (while lockin), then work on it.
Basically:
In your case, you lock in foo will only be released when foo is finished.