旷世难题:线程同步的时候写入的日志竟然有时间重合,怎么回事儿,高手请进

lcmlhs_2005 2010-09-21 11:06:44
代码如下:
Thread thd1, thd2;

private void writetxt(string strnr)
{
string Sendpath = Application.StartupPath + "\\" + "Send_log.txt";
lock (this)
{
FileStream FSSend = new FileStream(Sendpath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(FSSend);
sw.WriteLine(strnr);
sw.Close();
}
}

private void thdrun1()
{
DateTime currentTime = new DateTime();

while (true)
{
currentTime = DateTime.Now;
string strtime = currentTime.ToString("yyyy-MM-dd HH:mm:ss:fff");
string strnr = "thd1write: " +strtime;
writetxt(strnr);
}
}

private void thdrun2()
{
DateTime currentTime = new DateTime();

while (true)
{
currentTime = DateTime.Now;
string strtime = currentTime.ToString("yyyy-MM-dd HH:mm:ss:fff");
string strnr = "thd2write: " +strtime;
writetxt(strnr);
}
}

private void button1_Click(object sender, EventArgs e)
{
thd1 = new Thread(new ThreadStart(thdrun1));
thd2 = new Thread(new ThreadStart(thdrun2));
thd1.Start();
thd2.Start();

}
上面的程序执行后,在日志文件Send_log.txt里会找到thd1write与thd2write在同一时间里写入的记录,这是怎么回事儿啊?我加了锁了呀,在某一时间段里不能同时有两个进程写日志的啊,什么原因????????
...全文
542 66 打赏 收藏 转发到动态 举报
写回复
用AI写文章
66 条回复
切换为时间正序
请发表友善的回复…
发表回复
liangyi571 2010-10-24
  • 打赏
  • 举报
回复
这还不简单, 为什么非要以时间为唯一标识呢? 可以加个全局变量, 把这个变量放到时间后面, 全当它是微秒. 这样不行吗?
humaolin361975026 2010-09-27
  • 打赏
  • 举报
回复
lock
showjim 2010-09-26
  • 打赏
  • 举报
回复
大量线程排队不仅仅会造成CPU高,而且会可能不停的切换上下文(不做正事)造成假死,最后用单线程的队列做。
using System;
using System.Collections.Generic;
using System.Threading;
using System.Reflection;

namespace showjim.sys.threading
{
/// <summary>
/// 队列处理线程
/// </summary>
/// <typeparam name="valueType">队列处理值类型</typeparam>
public class queue<valueType>
{
#region 队列处理信息
/// <summary>
/// 队列处理信息
/// </summary>
private class queueInfo
{
/// <summary>
/// 待处理对象
/// </summary>
public valueType value;
/// <summary>
/// 处理委托
/// </summary>
public showjim.sys.run<valueType> onProcess;
}
#endregion

/// <summary>
/// 队列操作锁
/// </summary>
private object queueLock = new object();
/// <summary>
/// 待处理队列
/// </summary>
private List<queueInfo> queues = new List<queueInfo>();
/// <summary>
/// 队列处理线程
/// </summary>
private Thread queueThreadHandle;
/// <summary>
/// 处理委托
/// </summary>
private showjim.sys.run<valueType> onProcess;
/// <summary>
/// 暂停或恢复队列处理线程
/// </summary>
public bool _isPause = false;
/// <summary>
/// 暂停或恢复队列处理线程
/// </summary>
public bool isPause
{
set
{
if (value) close(true);
else add(null);
}
}

#region 初始化队列处理线程
/// <summary>
/// 初始化队列处理线程
/// </summary>
/// <param name="onProcess">处理委托</param>
public queue(showjim.sys.run<valueType> onProcess)
{
this.onProcess = onProcess;
}
#endregion

#region 关闭队列处理线程
/// <summary>
/// 关闭队列处理线程
/// </summary>
~queue() { close(false); }
/// <summary>
/// 关闭队列处理线程
/// </summary>
/// <param name="isPause">是否暂停队列处理线程</param>
public void close(bool isPause)
{
Thread handle = null;
Monitor.Enter(queueLock);
try
{
_isPause = isPause;
if (queueThreadHandle != null)
{
handle = queueThreadHandle;
queueThreadHandle = null;
if (!isPause) queues.Clear();
}
}
finally { Monitor.Exit(queueLock); }
if (handle != null && handle.IsAlive) handle.Abort();
}
#endregion

#region 添加待处理对象
/// <summary>
/// 添加待处理对象
/// </summary>
/// <param name="value">待处理对象</param>
public void add(valueType value) { add(new queueInfo { value = value, onProcess = null }); }
/// <summary>
/// 添加待处理对象
/// </summary>
/// <param name="value">待处理对象</param>
/// <param name="onProcess">处理委托</param>
public void add(valueType value, showjim.sys.run<valueType> onProcess) { add(new queueInfo { value = value, onProcess = onProcess }); }
/// <summary>
/// 添加待处理对象
/// </summary>
/// <param name="value">待处理对象信息</param>
private void add(queueInfo value)
{
Thread handle = null;
Monitor.Enter(queueLock);
try
{
if (this.onProcess != null || value == null || value.onProcess != null)
{
if (value != null) queues.Add(value);
if (queueThreadHandle == null && (value == null || !_isPause) && queues.Count != 0) handle = queueThreadHandle = new Thread(new ThreadStart(queueThread));
}
}
finally { Monitor.Exit(queueLock); }
if (handle != null)
{
handle.IsBackground = true;
handle.Start();
}
}
#endregion

#region 队列处理线程
/// <summary>
/// 队列处理线程
/// </summary>
public void queueThread()
{
for (queueInfo value = next(); value != null; value = next())
{
try { (value.onProcess == null ? this.onProcess : value.onProcess)(value.value); }
catch (Exception error) { showjim.sys.exception.debug.writeDebug(MethodBase.GetCurrentMethod(), typeof(valueType).FullName + " 队列处理失败", error); }
}
}
/// <summary>
/// 获取下一个待处理对象
/// </summary>
/// <returns>待处理对象</returns>
private queueInfo next()
{
queueInfo value = null;
Thread handle = null;
Monitor.Enter(queueLock);
if (queueThreadHandle != null && queues.Count != 0)
{
value = queues[0];
queues.RemoveAt(0);
}
else
{
handle = queueThreadHandle;
queueThreadHandle = null;
}
Monitor.Exit(queueLock);
if (handle != null)
{
if (handle.IsAlive)
{
try { handle.Abort(); }
catch { }
}
}
return value;
}
#endregion
}
}
jx0797 2010-09-26
  • 打赏
  • 举报
回复
1毫秒计算机可以做很多事了,这2个线程在1毫秒内做完了你想做的事,所以时间重复了···
lcmlhs_2005 2010-09-26
  • 打赏
  • 举报
回复
楼上的,不要打消我的钻研的积极性,还有上面的多线程开启后,CPU占用特别高,是怎么回事儿 ?
3000sunqin 2010-09-26
  • 打赏
  • 举报
回复
1.楼主使用毫秒级时间记录,肯定会出现重复,因为写日志的时间比毫秒级要短;
2.CPU占用高,是因为楼主的程序中线程根本不Sleep,当然会很高,线程是什么?是死循环,CPU能占用不高吗?
3.请在取时间的时候进行锁定操作,否则不可能不出现时间重复现象,如果你取时间的时候是重复的,你写日志再怎么锁也是重复的
yyd021 2010-09-24
  • 打赏
  • 举报
回复
楼主的牛角尖钻得很深,我表示无语了。
monkchen 2010-09-21
  • 打赏
  • 举报
回复
while (true)
{
currentTime = DateTime.Now;
string strtime = currentTime.ToString("yyyy-MM-dd HH:mm:ss:fff");
string strnr = string.Format("thd2write: [{0}][{1}]",strtime, Enviroment.TickCount); //这句改成这样,你看看最后的数字一不一样

writetxt(strnr);
}
ZengHD 2010-09-21
  • 打赏
  • 举报
回复
修改成下面这样
FileStream FSSend = new FileStream(Sendpath, FileMode.Append, FileAccess.Write, FileShare.None);
Dream83619 2010-09-21
  • 打赏
  • 举报
回复
DateTime的精度是16ms
lcmlhs_2005 2010-09-21
  • 打赏
  • 举报
回复
你是说我的程序正常吗?明明日志文件里有两个线程同时写日志的记录啊
yyd021 2010-09-21
  • 打赏
  • 举报
回复
Windows的API函数 QueryPerformanceCounter和QueryPerformanceFrequecy

/// <summary>
/// 获取2个时间点的时间中CPU运行的次数
/// </summary>
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

/// <summary>
/// 获取CPU频率
/// </summary>
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency); lpFrequency);


这两个函数可以精确计时,但是有一部分操作系统不支持,如win98等。而且程序自己运行要消耗一部分时间,可能会影响结果。

就上面这个问题是肯定是正常的,不可能会同时写入的。
lcmlhs_2005 2010-09-21
  • 打赏
  • 举报
回复
楼上的,这不是和同一时间只能一个线程能进入临界区相违背吗?这还是正常吗?
jimh 2010-09-21
  • 打赏
  • 举报
回复
没问题啊,这样很正常,时间精度就是这个级别了,两个线程没有执行太多代码,运行太快,时间精度不足,无法分清先后顺序。
lcmlhs_2005 2010-09-21
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 yyd021 的回复:]
你精确到7位没有用,因为返回值没有这么精确。
DateTime.Now的返回值只能精确到1%秒。
[/Quote]
那要用哪个时间来更精确
lhzyn 2010-09-21
  • 打赏
  • 举报
回复
两个进程么?那要用进程互斥Mutex
yyd021 2010-09-21
  • 打赏
  • 举报
回复
你精确到7位没有用,因为返回值没有这么精确。
DateTime.Now的返回值只能精确到1%秒。
lcmlhs_2005 2010-09-21
  • 打赏
  • 举报
回复
楼上的,我精确到七位,还是不行啊,如 string strtime = currentTime.ToString("yyyy-MM-dd HH:mm:ss:fffffff");这样还是不行,还有时间重合
yyd021 2010-09-21
  • 打赏
  • 举报
回复
你的时间精确到才到毫秒级别,1毫秒计算机可以做很多事情了,完全可以一个写完日志,然后另外一个再写一次。
damjmk2 2010-09-21
  • 打赏
  • 举报
回复
public class SynchThread
{
public void AddData(Object obj) //添加数据
{
MsgCacheList.Enqueue(obj); //加入队列
}

public void DealMsgQueue(Queue MsgCacheList) //处理命令队列
{
lock(MsgCacheList.SyncRoot)
{
Object item = MsgCacheList.Dequeue();
AddLog(item); //这里是你要实现写日志的函数
}
}

public static Queue MsgCacheList; //静态队列
}


此外 DealMsgQueue 方法需要用一个委托的方法实现
加载更多回复(46)

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧