#include <iostream>
#include <chrono>
#include <thread>
#include <mutex>
#ifndef TEST_MAX_NUMBER
#define TEST_MAX_NUMBER 200
#endif // !TEST_MAX_NUMBER
using namespace std;
int number = 1;
mutex g_lock;
bool IsPrimeNumber(const int inum)
{
bool bret = true;
for (int i = 2; i*i <= inum ; i++) {
if (0 == inum % i) {
bret = false;
break;
}
}
return bret;
}
int ThreadProc1()
{
while (number < TEST_MAX_NUMBER){
if (IsPrimeNumber(number)){
g_lock.lock();
cout << "thread 1 :" << number << " is prime number" << endl;
++number;
g_lock.unlock();
this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
return 0;
}
int ThreadProc2()
{
while (number < TEST_MAX_NUMBER){
if (false == IsPrimeNumber(number)) {
g_lock.lock();
cout << "thread 2 :" << number << " is composite number" <<endl;
++number;
g_lock.unlock();
this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
return 0;
}
int main()
{
thread t2(ThreadProc2);
thread t1(ThreadProc1);
t1.join();
t2.join();
system("pause");
return 0;
}
两个线程分别顺序输出1-200之内的素数和合数
最新推荐文章于 2024-04-07 15:01:44 发布