1、多线程队列实现
void initSrand()
{
LARGE_INTEGER start;
QueryPerformanceCounter(&start);
srand(unsigned(start.LowPart));
}
void initSrand1()
{
struct timeb tb;
ftime(&tb);
srand(unsigned(tb.millitm));
}
int cap=10;
deque<int> de;
condition_variable cv;
mutex mtx;
bool enqueue(int v)
{
unique_lock<mutex> lk(mtx);
while (de.size() >= cap)
{
cout << "deque is full... " << endl;
cv.wait(lk);
}
de.push_back(v);
cv.notify_all();
return true;
}
int dequeue()
{
unique_lock<mutex> lk(mtx);
while (de.size() == 0)
{
cout << "deque is empty... " << endl;
cv.wait(lk);
}
int tmp = de.front();
de.pop_front();
cv.notify_all();
return tmp;
}
void fen()
{
while (1)
{
Sleep(1000);
initSrand();
int tmp = rand();
enqueue(tmp);
cout << "push " << tmp << endl;
}
}
void fde()
{
while (1)
{
Sleep(1000);
int tmp=dequeue();
cout << "pop " << tmp << endl;
}
}
int main()
{
const int num1 = 10;
const int num2 = 5;
thread arr1[num1];
thread arr2[num2];
for (int i = 0; i < num1; i++)
{
arr1[i] = thread(fen);
}
for (int i = 0; i < num2; i++)
{
arr2[i] = thread(fde);
}
for (int i = 0; i < num1; i++)
{
arr1[i].join();
}
for (int i = 0; i < num2; i++)
{
arr2[i].join();
}
return 0;
}