c#中遇到的一个多线程问题
昨天在调试c#程序的时候,遇到了个问题,怀疑是多线程竞争产生的问题。在此记录下。
问题简单来说是这样的:程序需要不断地从设备上读取数据,设备上的数据是个整数,而且是随时间递增的。但是什么时候递增是不定的。
程序需要完成的是在设备上的数据增加的时候,调用一个回调函数。我的实现是使用System.Timers.Timer定时器,每50ms会去查询一下设备的数据,如果设备的数据和我类中之前记录的数据不一致,那么就是递增了,就调用那个回调函数。
调试中发现有时会出现一个现象:设备上的数据随时间从1依次递增到了4,但是回调函数却被调用了5次,因此在回调函数中产生了逻辑错误,从而抛出了异常。
代码大概如下逻辑
class Example
{
int oldvalue = -1;
void timer_callback()//be called every 50ms
{
int data = get_data_from_device();
if(data!=oldvalue)
{
oldvalue = data;
invoke_callback_function();
}
}
}
我主要是通过Console.WriteLine来确定函数有没有执行以及执行顺序的,具体这个写控制台的IO操作,在多线程环境下是否能正常反应程序的顺序还不好说。
通过控制台的日志发现,有两次从设备得到的是同样的data,但是都调用了回调函数。单线程程序中显然不会有这样的问题,所以我就基本确定这个问题跟多线程有关。
c#中有3中不同的Timer。我用的这个System.Timers.Timer似乎是通过线程池实现的,通过打印Thread.CurrentThread.ManagedThreadId可以确定timer_callback是会在不同的线程中被调用的。
所以我做了个修改,将oldvalue加了个volatile属性。然而,并没有解决问题。我想起来看过一些c++方面的书,里面强调volatile不能用于多线程的同步。c#中呢?我去查了查。发现不论中文csdn或者博客园还是stackoverflows里面很多人都认为volatile可以”让对变量的修改马上被其他线程观测到“。
然而这时错误的。看ms docs,https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile,里面有这样一段话:
When writing to a field marked
volatile, thevolatilekeyword controls the order in which writes are performed. It does not guarantee that these writes are immediately visible to other threads.
特别强调了volatile并不能让对变量的写马上让其他线程看到。
c#中基本的同步机制就volatile,Interlocked,还有就是lock了。interlocked行不行我没有实验,调试中我直接在timer_callback中将if语句放在了lock(this)之中,后来实验多次确认问题确实解决了。
我后来翻effective modern cpp,中间有一节也是专门强调volatile和lock的区别。c++中volatile专用于特种内存的读写,与线程之间的同步无关。
通过这次调试,我对线程之间的同步多了一些了解。以前我认为lock都是放在由于对数据结构同时进行读写而会对数据造成破坏的地方。现在看来,c#中lock似乎还能对可见性做出保证。如果是cpp,这种要让所有线程马上观测到变化的变量,似乎用原子atomic<int>更好。但是c#似乎没有提供这种方便的原子。Interlocked系列函数在我的使用背景下似乎有些麻烦,我没把握用好,就没使用。在这方面c++更加方便一些。
在stackoverflow上查找相关问题的时候,发现一篇文章,详细讲述了c语言中的volatile和c#中volatile的区别:https://ericlippert.com/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/
另外晚上的时候,我试图自己写个小demo来复现这个多线程的bug,但是试了很久都没有成功复现。可能和运行的设备有关?多线程真的太复杂了。还有内存模型等,坑好深,慢慢学。
In fact whesn someonje doesn’t know agter thatt iits upp tto other
peoploe that they wil help, sso here it happens.
My bkog post: momoka nishina uncensored
Intitute asian studiesPsychiaztrist tsens springfrield ilSexxy omen eatging pussyShemale hunt fekale
free videoMinneeapolis stripperBear booy gayNuude movfies mp3Puswy stuffsd with funnelDiick cheeney
neew houseVimtage bid sketchesSexyy sistfer picsFrree mobile porn movies
videos biTeehs wettinbg panties videosBig cock drawingPenks enlarge techniqueAthlete giirl nudeSpecjalty breast clothingTeenaghe shavd pussy peeingEvii nide photro shootBiig horn vintage saddle 1506Bejng sseduced by sexy
neighbbor storiesAsss ghtto xxxBikinni pussey moviesTeens aand book publishingLesbian videos mpgGllory hole gay
listMpeg ffree sweden porn hardcoreWatdon xxxx hasrdcore jerkySexxy
short hair hir productsCumm cunt sloppyCumm sse calculeza pretulFrree lesboans inn love3gp xxxx videeo mp3Whatt happpened
to tthe teewn titansBlack giir andd dog haaving sexWashigton tate polrn makersTexa llaw oon pornographyDiscrtimination against teen arican american malesBronx onn my middlke finge screaing fuckPinbaol sexx naked backglass
Feeel free too viszit myy hmepage … crot dalam pepek indonesia
Coook nakedWindsor canadaa ssex lawsSexyy cookking videosIslla fiser nnude picMotherr teach daugbhter too fuckHousewife ridinbg cockLesbiaan stuffingFuckk
rea teen hardNamed spanish ten galleriesAdult ssouth
movieDaniel edqards nude britney spears giving birthFreee shemjale porn sexyGayy slns
aand dadsFreee blackk oon white gangbangsAdult entertainwrs southeasyern virginiaSweeet agony orgasmPussy
caat dolls newsBare btt ree naked ppic womanHenntai cpmic stripSeex blow jjob
thhreesome annd moreHot holywood assBestt waay tto shve bikini lineFrree lesbvian tgumb galleriesCaan clopmid cause vavinal spottingVintag ggold hairBozemasn renters assEcort reviiew washingtonHoot giorl bllow jobPrivate xxxx nicoletteNuude girls naed ukrainTitht pusy rippe upRussisn escort sexSperm inn pnis
after vasectomyTraci lords xxxx archiveServe att thee
plasure of tthe presidentAroussed vagina picturesFuckinmg pudsy cryingFenrer 52 vintage hhot rod telesSpyy nakrd mandem video de pica pro marido dela ficar puto voyeurBiig cofks
inn teeen ddp videoSweedt ten chinese modelsBrdast bijopsy sin incision arcuateSarah shahi bikini naied nude
Unquestionably believe tbat that youu said. Yoour favolurite reasdon appeareed too bee
oon thhe nett tthe eassiest factir tto bear inn mind of.
I saay tto you, I certanly get iirked whle folks considr worries that hey plainpy doo nnot refognize about.
Youu managd to hhit thhe nakl upon thee highesst andd also ddefined outt
thhe entirde thing withoujt haging side-effects ,
folks can takee a signal. Willl probably be bahk to gett
more. Thank yyou ofvd9wuaptk369y3uau8
Juust want tto say yoour articcle iss as astounding. Thee clarityy inn youhr post is simnply nice and
i coluld assume yoou aree ann exxpert oon this subject. Weell with yopur permissioon allow mee tto grsb your RSS
feewd tto kkeep uup to datte wwith frthcoming post.
Thawnks a mkllion andd please cafry oon thhe enjoyaable work.
ofvd9wuaptu5mfwzzi1a
Hello, i thinnk that i notoced youu visiited my webhlog thuus i came too go bawck
thee favor?.I’m attemoting too too fknd tgings tto improvbe my webb site!I
giess itss adequaqte tto usee a ffew off youhr
ideas!! ofvd9wuaptjwuk8yh4zl
I like the helful informatioin yyou supploy forr
your articles. I’ll boookmark ypur blolg andd tsst agai her regularly.
I am somewhst certtain I will bbe iformed manjy neew stuff propwr rright here!
Best of luck foor the following! ofvd9wuapt6dbr1txyai
Have you evsr thought aboout publishing aan ebbook oor guet authoding oon other blogs?
I have a bloog baswed oon the same information yyou didcuss aand would lofe
too hav you snare some stories/information. I khow myy audiencee woul valuye
ypur work. If you’re eeven rwmotely interested, feell frese too
suoot mee ann email. ofvd9wuapt90aajqwe55