容器我用的是Dictionary<TKey,TValue>,有一个线程对这个容器进行写操作,另一个线程则对这个容器进行读操作
我用的Monitor来对这个容器进行加锁/读锁,
//这是需要传递的对象
class info
{
int infono = -1;
staticinfo sf;
public info()
{
sf = new staticinfo();
}
}
class staticinfo
{
string name = string.Empty;
}//写操作线程
class writeWork
{
Dictionary<int,info> dic;
public writeWork()
{
dic = new Dictionary<int,info>();
}
public Dictionary<int,info> m_Dic
{ get{return dic;}
}
pulic void doWrite()
{
while()
{
info in = new info();
Monitor.Enter(dic)
try
{
//填充info内容
dic.Add(in.infono,info);
}finaly
{
Monitor.Exit(dic);
}
dic.Add(in.info,info);
} {
}//读取操作
class readWork
{
writeWork write = new writeWork();
public void read()
{
Monitor.Enter(write.m_Dic);
try
{
foreach(info inf in write.m_Dic.values)
{
//读取操作
}
}finaly
{
Monitor.Exit(write.m_Dic);
}
}
}不知道我这样写对不对,这个思路运行是没有问题的,但是我总感觉似乎线程通讯有些问题,但又不知道该怎么解决,哪位高手能否给看一下.
我用的Monitor来对这个容器进行加锁/读锁,
//这是需要传递的对象
class info
{
int infono = -1;
staticinfo sf;
public info()
{
sf = new staticinfo();
}
}
class staticinfo
{
string name = string.Empty;
}//写操作线程
class writeWork
{
Dictionary<int,info> dic;
public writeWork()
{
dic = new Dictionary<int,info>();
}
public Dictionary<int,info> m_Dic
{ get{return dic;}
}
pulic void doWrite()
{
while()
{
info in = new info();
Monitor.Enter(dic)
try
{
//填充info内容
dic.Add(in.infono,info);
}finaly
{
Monitor.Exit(dic);
}
dic.Add(in.info,info);
} {
}//读取操作
class readWork
{
writeWork write = new writeWork();
public void read()
{
Monitor.Enter(write.m_Dic);
try
{
foreach(info inf in write.m_Dic.values)
{
//读取操作
}
}finaly
{
Monitor.Exit(write.m_Dic);
}
}
}不知道我这样写对不对,这个思路运行是没有问题的,但是我总感觉似乎线程通讯有些问题,但又不知道该怎么解决,哪位高手能否给看一下.
private Mutex mReader = new Mutex();
private int nReader = 0;//Writer operate
mReader.WaitOne();//Get mutex to avoid other entering read block
mWriter.WaitOne();//Get mutex to enter write block//Write operation heremWriter.ReleaseMutex();//Release mutex after leaving write block
mReader.ReleaseMutex();//Release mutex to allow other enter read block
//Reader operate
mReader.WaitOne();//Get mutex to enter reader block
nReader++;
if( nReader == 1 )//First enters reader block
mWriter.WaitOne();//Avoid to be write
mReader.ReleaseMutex();// Allow other to enter//Read operation heremReader.WaitOne();//Get mutex to enter reader block
nReader--;
if( nReader == 0 )//The last leaves reader block
mWriter.ReleaseMutex();//Release mutex to allow other enter write block
mReader.ReleaseMutex();// Allow other to enter
首先感谢对我这个问题的回答.我问的问题就是一个对容器的操作
也就是说对这个容器进行写入和读取的操作但是把容器放在什么地方,单独作为一个静态类来存放还是作为写入线程的成员变量,这会有什么区别,或者还有更好的办法? 运行的时候是否能保证数据的同步?
上面您说给出的是Mutex互斥函数调用
能否再给一段用Mutex对类或变量或代码段的操作的代码呢?
网上的确很多 我用Monitor try...finaly 其实和lock(this)是一样的道理啊