同步是一种只允许一个线程在特定时间访问某些资源的技术。没有其他线程可以中断,直到所分配的线程或当前访问线程访问数据完成其任务。
在多线程程序中,允许线程访问任何资源所需的执行时间。线程共享资源并异步执行。 访问共享资源(数据)是有时可能会暂停系统的关键任务。所以可以通过线程同步来处理它。
主要场景如:存款,取款等交易业务处理。
使用 c# lock
关键字同步执行程序。它用于为当前线程锁定,执行任务,然后释放锁定。它确保其他线程在执行完成之前不会中断执行。
下面,创建两个非同步和同步的例子。
在这个例子中,我们不使用锁。此示例异步执行。换句话说,线程之间存在上下文切换。
using system;
using system.threading;
class printer
{
public void printtable()
{
for (int i = 1; i <= 5; i++)
{
thread t = thread.currentthread;
thread.sleep(200);
console.writeline(t.name+" "+i);
}
}
}
class program
{
public static void main(string[] args)
{
printer p = new printer();
thread t1 = new thread(new threadstart(p.printtable));
thread t2 = new thread(new threadstart(p.printtable));
t1.name = "thread 1 :";
t2.name = "thread 2 :";
t1.start();
t2.start();
}
}
执行上面示例代码,可以看到以下输出结果 -
thread 2 : 1
thread 1 : 1
thread 2 : 2
thread 1 : 2
thread 2 : 3
thread 1 : 3
thread 2 : 4
thread 1 : 4
thread 2 : 5
thread 1 : 5
在这个例子中,我们使用lock
块,因此示例同步执行。 换句话说,线程之间没有上下文切换。在输出部分,可以看到第二个线程在第一个线程完成任务之后开始执行。
using system;
using system.threading;
class printer
{
public void printtable()
{
lock (this)
{
for (int i = 1; i <= 5; i++)
{
thread t = thread.currentthread;
thread.sleep(100);
console.writeline(t.name + " " + i);
}
}
}
}
class program
{
public static void main(string[] args)
{
printer p = new printer();
thread t1 = new thread(new threadstart(p.printtable));
thread t2 = new thread(new threadstart(p.printtable));
t1.name = "thread 1 :";
t2.name = "thread 2 :";
t1.start();
t2.start();
}
}
执行上面示例代码,可以看到以下输出结果 -
thread 1 : 1
thread 1 : 2
thread 1 : 3
thread 1 : 4
thread 1 : 5
thread 2 : 1
thread 2 : 2
thread 2 : 3
thread 2 : 4
thread 2 : 5