死锁1:
std::mutex mx; //互斥量
std::condition_variable cv; //信号量
int number = 0;
const int n = 3;
void func1()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3 == 0 && number <=n)
{
cout << "fun1: " << number << " " << endl;
number += 1;
cv.notify_one();
}
cv.wait(lock);
}
}
void func2()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3 == 1 && number <= n)
{
cout << "fun2: " << number << " " << endl;
number += 1;
cv.notify_one();
}
cv.wait(lock);
}
}
void func3()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3== 2&& number <= n)
{
cout << "fun3: " << number << " " << endl;
number += 1;
cv.notify_one();
}
cv.wait(lock);
}
}
int main()
{
thread tha(func1);
thread thb(func2);
thread thc(func3);
tha.join();
thb.join();
thc.join();
return 0;
}
死锁2:
std::mutex mx; //互斥量
std::condition_variable cv; //信号量
int number = 0;
const int n = 3;
void func1()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3 == 0 && number <=n)
{
cout << "fun1: " << number << " " << endl;
number += 1;
cv.notify_all();
}
cv.wait(lock);
}
}
void func2()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3 == 1 && number <= n)
{
cout << "fun2: " << number << " " << endl;
number += 1;
cv.notify_all();
}
cv.wait(lock);
}
}
void func3()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3== 2&& number <= n)
{
cout << "fun3: " << number << " " << endl;
number += 1;
cv.notify_all();
}
cv.wait(lock);
}
}
int main()
{
thread tha(func1);
thread thb(func2);
thread thc(func3);
tha.join();
thb.join();
thc.join();
return 0;
}
说明还有进程在等待队列上,无法正常退出
修改正常:程序最终在唤醒一次
std::mutex mx; //互斥量
std::condition_variable cv; //信号量
int number = 0;
const int n = 3;
void func1()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3 == 0 && number <=n)
{
cout << "fun1: " << number << " " << endl;
number += 1;
cv.notify_one();
}
cv.wait(lock);
}
cv.notify_one();
}
void func2()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3 == 1 && number <= n)
{
cout << "fun2: " << number << " " << endl;
number += 1;
cv.notify_one();
}
cv.wait(lock);
}
cv.notify_one();
}
void func3()
{
std::unique_lock<mutex>lock(mx);
while (number <= n)
{
while (number % 3== 2&& number <= n)
{
cout << "fun3: " << number << " " << endl;
number += 1;
cv.notify_one();
}
cv.wait(lock);
}
cv.notify_one();
}
int main()
{
thread tha(func1);
thread thb(func2);
thread thc(func3);
tha.join();
thb.join();
thc.join();
return 0;
}