0
我在C小白++,并有一个类(mystack),有一个在它的方法(推),它可以使用如何在不同的线程中调用同一类的多个对象的方法?
mystack a;
a.push();
现在我已经创造了A类的多个实例调用,并为他们每个人我想调用push方法,我想知道如何在不同的线程中调用它们,谢谢。
编辑
完整的代码如下(这是很长,但很简单明了),有类mystack的两个实例,他们每个人提方法调用的顺序,我要让方法在不同的线程中调用不同的实例,所以我想在一个线程中执行实例stc的push和pop操作,并且在另一个线程中执行stc2中的相同操作,那么我将如何实现这一点?
#include "stdafx.h"
#include <string>
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
using namespace std;
//static recursive_mutex mtx;
struct mystack
{
int *p;
unsigned int limit, counter;
public:
unsigned int max()
{
return limit;
}
~mystack()
{
delete p;
}
mystack(int k) : limit(k), p(0), counter(0)
{
if (limit > 0)
{
p = new int[limit];
}
}
void push(unsigned int k)
{
if (counter >= limit)
{
throw 1;
}
p[counter] = k;
counter++;
}
int pop()
{
if (counter <= 0)
{
throw 1;
}
counter--;
return p[counter];
}
};
int main(int, char*[])
{
mystack stc(5);
try
{
stc.push(1);
stc.push(2);
stc.push(3);
stc.push(4);
stc.push(5);
stc.push(6);
}
catch (int i)
{
try
{
cout << "pop out the values" << endl;
while (true)
{
cout << stc.pop() << " ";
}
}
catch (int j)
{
cout << endl;
cout << "stack is now empty" << endl;
cout << endl;
}
}
mystack stc2(3);
try
{
stc2.push(1);
stc2.push(2);
stc2.push(3);
stc2.push(4);
stc2.push(5);
stc2.push(6);
}
catch (int i)
{
try
{
cout << "pop out the values" << endl;
while (true)
{
cout << stc2.pop() << " ";
}
}
catch (int j)
{
cout << endl;
cout << "stack is now empty" << endl;
cout << endl;
}
}
return 0;
}
非常感谢你! – photosynthesis 2014-12-06 04:17:00