会员
周边
众包
新闻
博问
闪存
赞助商
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
Try again
博客园
首页
联系
管理
应用程序中的所有线程都可以访问方法中的公用字段。要同步对公用字段的访问,您可以使用属性替代字段,并使用 ReaderWriterLock 对象控制访问。为此,请按照下列步骤操作:
using
System;
using
System.Threading;
namespace
MultiThreadApplication
{
class
Class1
{
private
ReaderWriterLock rwl
=
new
ReaderWriterLock();
private
long
myNumber;
public
long
Number
//
the Number property
{
get
{
//
Acquire a read lock on the resource.
rwl.AcquireReaderLock(Timeout.Infinite);
try
{
Console.WriteLine(
"
Thread:{0} starts getting the Number
"
, Thread.CurrentThread.GetHashCode());
Thread.Sleep(
50
);
Console.WriteLine(
"
Thread:{0} got the Number
"
, Thread.CurrentThread.GetHashCode());
}
finally
{
//
Release the lock.
rwl.ReleaseReaderLock();
}
return
myNumber;
}
set
{
//
Acquire a write lock on the resource.
rwl.AcquireWriterLock(Timeout.Infinite);
try
{
Console.WriteLine(
"
Thread: {0} start writing the Number
"
, Thread.CurrentThread.GetHashCode());
Thread.Sleep(
50
);
myNumber
=
value;
Console.WriteLine(
"
Thread: {0} written the Number
"
, Thread.CurrentThread.GetHashCode());
}
finally
{
//
Release the lock.
rwl.ReleaseWriterLock();
}
}
}
[STAThread]
static
void
Main(
string
[] args)
{
Thread[] threadArray
=
new
Thread[
20
];
int
threadNum;
Class1 Myclass
=
new
Class1();
ThreadStart myThreadStart
=
new
ThreadStart(Myclass.AccessGlobalResource);
//
Create 20 threads.
for
(threadNum
=
0
; threadNum
<
20
; threadNum
++
)
{
threadArray[threadNum]
=
new
Thread(myThreadStart);
}
//
Start the threads.
for
(threadNum
=
0
; threadNum
<
20
; threadNum
++
)
{
threadArray[threadNum].Start();
}
//
Wait until all the thread spawn out finish.
for
(threadNum
=
0
; threadNum
<
20
; threadNum
++
)
threadArray[threadNum].Join();
Console.WriteLine(
"
All operations have completed. Press enter to exit
"
);
Console.ReadLine();
}
public
void
AccessGlobalResource()
{
Random rnd
=
new
Random();
long
theNumber;
if
(rnd.Next()
%
2
!=
0
)
theNumber
=
Number;
else
{
theNumber
=
rnd.Next();
Number
=
theNumber;
}
}
}
}
说明了读写共享资源访问是不冲图的,如下图所示(这个方式解决了多个线程可同时读,只有一个线程可以定的操作的协调)
posted on
2006-04-29 09:00
共同学习,共同进步
阅读(
306
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
Powered by:
博客园
Copyright © 2024 共同学习,共同进步
Powered by .NET 8.0 on Kubernetes