当前位置: 首页 > 工具软件 > CODE2RACE > 使用案例 >

面试向:What‘s race condition and how to avoid it?

郎琪
2023-12-01

We do know what this race condition topic is related with multithreading.

first, what’s race condition?
when two or more threads trying to get access (read or write) the same section. and the results is related to the order of the execution of different threads【当两个或更多线程都能同时获取以及改变共享数据时,竞争危害便发生了。因为各个线程对数据操纵的顺序并不可预知,因此数据改变的结果取决于线程最终的运行顺序。所有的线程都在“Racing”(竞争)以优先获取数据改变数据。】.
so this situation, will be called “race condition”.

what’s the diff with deadlock?
deadlock means that both of two threads holds one resource and want to resource of each other. so, everyone is waiting each other to release the lock on the resource.

两者都是多线程下面的不好的情况
所以 race condition强调不同的顺序执行不同的thread会带来不同的结果(因为没锁 同时竞争)
而deadlock是强调双方因为有锁而陷入了死局。

How to avoid it?
since we know why race condition happens, so it’s easy to fix it.
Just add synchronized keyword, to show that one time there’s only one thread can access it this code block/object/

 类似资料: