Created
March 1, 2015 13:07
-
-
Save antonshilov/017f4b6228d96a7c5f2f to your computer and use it in GitHub Desktop.
Lab3 question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "gun.h" | |
class gun { | |
public: | |
gun() { | |
mutex = PTHREAD_MUTEX_INITIALIZER; | |
setisloaded(true); | |
} | |
bool isgunloaded() const { | |
return isloaded; | |
} | |
void load() { | |
pthread_mutex_trylock(&mutex); | |
setisloaded(true); | |
sleep(loadtime); | |
pthread_mutex_unlock(&mutex); | |
} | |
void shot() { | |
pthread_mutex_trylock(&mutex); | |
setisloaded(false); | |
sleep(shottime); | |
pthread_mutex_unlock(&mutex); | |
} | |
private: | |
int shottime = 1; | |
int loadtime = 3; | |
bool isloaded; | |
pthread_mutex_t mutex; | |
void setisloaded(bool isloaded) { | |
this->isloaded = isloaded; | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void *gunner(void *arg) { | |
vector<gun> *v = static_cast<vector<gun> *>(arg); | |
srand(time(0)); | |
do { | |
for (int i = 0; i < v->size(); i++) { | |
if ((*v)[i].isGunLoaded() == true) {//Будет ли заблокирован поток, если в другом потоке в этот момент. (*v)[i] будет заблокирован( вызван метод gun.load() )? | |
cout << (*v)[i].isGunLoaded()<<" gun - " << i<< endl; | |
if (rand() % 2) { | |
(*v)[0].shot(); | |
cout << "BANG!" << endl; | |
} | |
} | |
} | |
} | |
while (true); | |
} | |
void *loader(void *arg) { | |
vector<gun> *v = static_cast<vector<gun> *>(arg); | |
do { | |
for (int i = 0; i < v->size(); i++) { | |
if ((*v)[i].isGunLoaded() == false) { | |
cout << (*v)[i].isGunLoaded()<<" gun - " << i << endl; | |
(*v)[i].load(); | |
cout << "Load!" << endl; | |
} | |
} | |
} | |
while (true); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment