C#多线程同步lock、Mutex的实现
class TestHelper
{
public TestHelper() { }
List<People> m_data = new List<People>();
int m_iComplete;
private void LockThread(object obj)
{
List<object> parameters = (List<object>)obj;
int idx = (int)parameters[0];
while (true)
{
People data = null;
lock(this)
{
if (m_iComplete >= m_data.Count)
{
return;
}
data = m_data[m_iComplete];
Interlocked.Increment(ref m_iComplete);
data.age = data.id;
Console.Write("======");
Console.WriteLine("id:" + data.id.ToString() + ",age:" + data.age.ToString());
}
}
}
//测试lock
public void TestLock()
{
DateTime time1 = DateTime.Now;
m_iComplete = 0;
m_data.Clear();
for (int i = 0; i < 10000;i++)
{
m_data.Add(new People(i + 1));
}
List<Thread> threads = new List<Thread>();
for (int i = 0; i < Environment.ProcessorCount; i++)
{
Thread th = new Thread(LockThread);
th.IsBackground = true;
List<object> objs = new List<object>();
objs.Add(i + 1);
th.Start(objs);
threads.Add(th);
}
foreach (var th in threads)
{
th.Join();
}
DateTime time2 = DateTime.Now;
TimeSpan deltaTime = time2.Subtract(time1);
Console.Write("===================耗时: ");
Console.WriteLine(deltaTime.TotalSeconds);
}
Mutex m_mutex = new Mutex();
private void MutexThread(object obj)
{
List<object> parameters = (List<object>)obj;
int idx = (int)parameters[0];
while (true)
{
People data = null;
//开启
m_mutex.WaitOne();
if (m_iComplete >= m_data.Count)
{
//释放
m_mutex.ReleaseMutex();
return;
}
data = m_data[m_iComplete];
Interlocked.Increment(ref m_iComplete);
data.age = data.id;
Console.Write("======");
Console.WriteLine("id:" + data.id.ToString() + ",age:" + data.age.ToString());
//释放
m_mutex.ReleaseMutex();
}
}
//测试mutex
public void TestMutex()
{
DateTime time1 = DateTime.Now;
m_iComplete = 0;
m_data.Clear();
for (int i = 0; i < 10000; i++)
{
m_data.Add(new People(i + 1));
}
List<Thread> threads = new List<Thread>();
for (int i = 0;i<Environment.ProcessorCount;i++)
{
Thread th = new Thread(MutexThread);
List<object> objs = new List<object>();
objs.Add(i + 1);
th.Start(objs);
threads.Add(th);
}
foreach(var th in threads)
{
//同步等待
th.Join();
}
DateTime time2 = DateTime.Now;
TimeSpan deltaTime = time2.Subtract(time1);
int sec = (int)deltaTime.TotalSeconds;
Console.Write("===================耗时: ");
Console.WriteLine(deltaTime.TotalSeconds);
}
}
- .NET Core系列之MemoryCache 初识
- 007手机一键Root(安机网一键Root) v3.0 官方最新版 一键ROOT您的Android手机
- 12306密码被盗了怎么办?12306密码外泄解决方法
- 12个字的qq网名
- 150M迷你型无线路由器怎么设置?
- 192.168.1.1打不开怎么办?路由器192.168.1.1打不开的原因以及解决办法
- 2011年电子报合订本 电子报 编辑部 中文 PDF版 [84M]
- 2015年1月15日小米新旗舰发布会现场图文直播
- 2016.3.1vivo Xplay5新品发布会现场视频直播 优酷直播
- 2016华为P9发布会视频直播地址 4月15日华为P9国行发布会直播