- 1、本文档共12页,可阅读全部内容。
- 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
实验二 线程与同步
实验目的
实现Nachos的同步机制:锁和条件变量,并利用这些同步机制实现一些工具类。
实验内容
(1)实现锁机制和条件变量
(2)实现一个线程安全的表结构
(3)实现一个大小受限的缓冲区
实验步骤
3.1实现锁机制和条件变量
用Thread::Sleep实现锁机制和条件变量
对synch.h做一下修改后保存为synch-sleep.h:
class Lock {
public:
Lock(char* debugName,int initialValue); // initialize lock to be FREE
~Lock(); // deallocate lock
char* getName() { return name; } // debugging assist
void Acquire(); // these are the only operations on a lock
void Release(); // they are both *atomic*
bool isHeldByCurrentThread(); // true if the current thread
// holds this lock. Useful for
// checking in Release, and in
// Condition variable ops below.
private:
char* name;
int value;
List *queue;
Thread *current;
// for debugging
// plus some other stuff youll need to define
};
class Condition {
public:
Condition(char* debugName); // initialize condition to
// no one waiting
~Condition(); // deallocate the condition
char* getName() { return (name); }
void Wait(Lock *conditionLock); // these are the 3 operations on
// condition variables; releasing the
// lock and going to sleep are
// *atomic* in Wait()
void Signal(Lock *conditionLock); // conditionLock must be held by
void Broadcast(Lock *conditionLock);// the currentThread for all of
// these operations
private:
char* name;
List *queue;
// plus some other stuff youll need to define
};
对synch.cc进行修改,实现其中未实现的函数,保存为synch-sleep.cc:
Lock::Lock(char* debugName,int initialValue)
{
name = debugName;
value = initialValue;
queue = new List;
}
Lock::~Lock()
{
delete queue;
}
void Lock::Acquire()
{
IntStatus oldLevel = interrupt-SetLevel(IntOff);
while (value == 0)
{ // semaphore not available
queue-Append((void *)currentThread);
currentThread-Sleep();
}
value--;
current=currentThread;
(void) interrupt-SetLevel(oldLevel);
}
void Lock::Release()
{
Thread *thread;
ASSERT(isHeldByCurrentThread()==tru
文档评论(0)