【发布时间】:2019-01-25 07:10:09
【问题描述】:
我不会说英语,我会使用翻译。
我在想什么时候学习线程同步。
class MainApp
{
static public int count = 0;
static private object tLock = new object();
static void plus()
{
for (int i = 0; i < 100; i++)
{
lock (tLock)
{
count++;
Console.WriteLine("plus " + count);
Thread.Sleep(1);
}
}
}
static void minus()
{
for (int i = 0; i < 100; i++)
{
lock (tLock)
{
count--;
Console.WriteLine("minus " + count);
Thread.Sleep(1);
}
}
}
static void Main()
{
Thread t1 = new Thread(new ThreadStart(plus));
Thread t2 = new Thread(new ThreadStart(minus));
t1.Start();
t2.Start();
}
}
简单的线程学习。
静态私有对象 tLock = new object();
lock(tLock)
【问题讨论】:
-
要在锁线程安全中创建语句?
-
旁注:
Console.WriteLine($"plus {Interlocked.Increment(ref count)}");是一种更快的实现方式(如果可能,请避免使用显式lock) -
这样你可能可以定义一个锁定对象,就像你发布的那样,而不是锁定要在同步下更新的实际对象......这可能会导致死锁
-
你是在问为什么需要锁或者为什么需要提供一个对象作为它的参数?
-
对不起。我想我写的问题太短了。已更正。
标签: c# multithreading synchronization locking