首页 > 试题广场 >

写一个类 A,它包含一个长度为 10 的整型数组,一个函数,

[问答题]
写一个类 A,它包含一个长度为 10 的整型数组,一个函数,可以插入数据到数组尾,另一个函数,可以取 得数组的第一个数据。写一个类,调用 A 的方法插入数据。写一个类,调用 A 的方法得到数据。要求使用多线程。
#include "pthread.h" #include "unistd.h" #include <iostream> using namespace std; #define SIZE 10 class A{ private: int arry[SIZE]; int pos; pthread_mutex_t mutex; pthread_cond_t notfull; pthread_cond_t notempty; public: A(); ~A(); int getLast(); void setFirst(int element); }; A::A(): pos(0){ pthread_mutex_init(&mutex, NULL); pthread_cond_init(&notfull, NULL); pthread_cond_init(&notempty, NULL); } A::~A(){ pthread_mutex_destory(&mutex); pthread_cond_destory(&notfull); pthread_cond_destory(&notempty); } int A::getLast(){ int returntmp; pthread_mutex_lock(&mutex); if(pos < 1) pthread_cond_wait(&notempty, &mutex); returntmp = arry[pos]; pos--; pthread_cond_signal(&notfull); pthread_mutex_unlock(&mutex); return returntmp; } void A::setFirst(int element){ pthread_mutex_lock(&mutex); if(pos > SIZE - 1) pthread_cond_wait(&notfull, &mutex); for(int i = pos+1;i > 0;--i) arry[i] = arry[--i]; arry[0] = element; pos++; pthread_cond_signal(&notempty); pthread_mutex_unlock(&mutex); } A a; void *put(int n) { for(int i = 0;i < SIZE; ++i) a.setFirst(n); } void *get() { for(int i = 0;i < SIZE; ++i) cout<<a.getLast(); cout<<endl; } int main(){ pthread_t pt1, pt2; pthread_create(&pt1, NULL, put, 0); pthread_create(&pt2, NULL, get, 0); return 0; }
发表于 2016-06-10 10:17:10 回复(0)