微软笔试题 spin lock, 请赐教

kernelkoder 2015-03-30 03:19:16

Spin lock
Let’s assume the existence of the following function in C++:
int InterlockedExchange(LPINT target, INT value);
or in C#:
class Interlocked
{
public static int Exchange (ref int target, int value);
}
This function atomically exchanges a pair of 32-bit values by writing the new value at the position pointed by
target, and returning the prior value of the int value pointed to by target.
Using this function, we want to implement a SpinLock class that can be used as a thread synchronization
mechanism to synchronize the access when multiple threads concurrently execute code that writes to or
modifies the same resource.
The SpinLock class should have the following interface:
class SpinLock
{
public:
void Enter(); // acquire the spinlock
void Exit(); // release the spinlock
};
For example, assume there is a variable (sharedValue) accessed and modified by a function
(threadSafeFunction()). Since this function may be concurrently executed by several threads, we can use a
SpinLock to make the function thread- safe in the following way:
static int sharedValue; // shared resource
static SpinLock lock; // lock for the resource
void threadSafeFunction() // executed by multiple threads
{
lock.Enter();
//
// some code that accesses sharedValue
//
lock.Exit();
}
Implement the class SpinLock either in C++ or in C#.
...全文
294 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
panghuhu250 2015-04-28
  • 打赏
  • 举报
回复
引用 1 楼 my_live_123 的回复:
考的这么深入,本因为是要写底层,但是题目的意思,用开篇提到的已存在的函数实现

int lockval = 1;//初始化值
enter()
{
       while(lockval); //如果锁一直上锁状态,则死循环等待,如果某瞬间此锁已经开锁,则上锁
       Exchange(lockval, 1); //上锁
}

exit()
{
       Exchange(lockval, 0);//开锁
}
exchange(lockval, 1)后还要再检查返回值, 如果是1, 说明其它thread已经抢先了, 再接着等.
一根烂笔头 2015-04-28
  • 打赏
  • 举报
回复
引用 2 楼 panghuhu250 的回复:
[quote=引用 1 楼 my_live_123 的回复:] 考的这么深入,本因为是要写底层,但是题目的意思,用开篇提到的已存在的函数实现

int lockval = 1;//初始化值
enter()
{
       while(lockval); //如果锁一直上锁状态,则死循环等待,如果某瞬间此锁已经开锁,则上锁
       Exchange(lockval, 1); //上锁
}

exit()
{
       Exchange(lockval, 0);//开锁
}
exchange(lockval, 1)后还要再检查返回值, 如果是1, 说明其它thread已经抢先了, 再接着等.[/quote] 是有这么个点,多谢指教 patch:

- while(lockval);
- Exchange(lockval, 1); //上锁

+while(Exchange(lockval, 1) == 1); //如果一直上锁状态,那么返回值一直是1,==1在C语言中也可以省略,如果某瞬间开锁,那么它枷锁,返回0,循环结束
一根烂笔头 2015-04-25
  • 打赏
  • 举报
回复
考的这么深入,本因为是要写底层,但是题目的意思,用开篇提到的已存在的函数实现

int lockval = 1;//初始化值
enter()
{
       while(lockval); //如果锁一直上锁状态,则死循环等待,如果某瞬间此锁已经开锁,则上锁
       Exchange(lockval, 1); //上锁
}

exit()
{
       Exchange(lockval, 0);//开锁
}

33,012

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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