代码程序
#include <iostream>
#include <mutex>
#include <list>
#include <thread>
using namespace std;
#define THREAD_BY_CLASS
#define MUTEX
#ifdef MUTEX
std::mutex MyMutex;
#endif
std::list<int> mlDataShared;
void InputData(void)
{
for (int i = 0, iend = 1000; i < iend; i++)
{
#ifdef MUTEX
MyMutex.lock();
#endif
cout << "插入第" << i + 1 << "个数据 : " << i << endl;
mlDataShared.push_back(i);
#ifdef MUTEX
MyMutex.unlock();
#endif
}
}
void OutputData(void)
{
for (int i = 0, iend = 1000; i < iend; i++)
{
#ifdef MUTEX
MyMutex.lock();
#endif
cout << "输出第" << i + 1 << "个数据: " << i << endl;
mlDataShared.pop_front();
#ifdef MUTEX
MyMutex.unlock();
#endif
}
}
class DataProcess {
public:
void InputData(void)
{
for (int i = 0, iend = 1000; i < iend; i++)
{
#ifdef MUTEX
MyMutex.lock();
#endif
cout << "插入第" << i + 1 << "个数据 : " << i << endl;
mlDataShared.push_back(i);
#ifdef MUTEX
MyMutex.unlock();
#endif
}
}
void OutputData(void)
{
while (1)
{
if (!mlDataShared.empty())
{
#ifdef MUTEX
MyMutex.lock();
#endif
cout << "输出第" << iCount++ << "个数据: " << mlDataShared.front() << endl;
mlDataShared.pop_front();
#ifdef MUTEX
MyMutex.unlock();
#endif
}
else
{
iCount = 0;
}
}
}
private:
#ifdef MUTEX
std::mutex MyMutex;
#endif
std::list<int> mlDataShared;
int iCount;
};
int main(int argc, char** argv) {
#ifdef THREAD_BY_CLASS
class DataProcess myclass;
std::thread inputThread(&DataProcess::InputData, ref(myclass));
std::thread outputThread(&DataProcess::OutputData, ref(myclass));
#endif
#ifdef TRREAD_BY_FUNCTION
cout << "jlm" << endl;
thread inputThread(InputData);
thread outputThread(OutputData);
#endif
inputThread.join();
outputThread.join();
std::cout << "Data Processed" << std::endl;
return 0;
}