为什么当count++或count——后面的printf没有注释时程序还能工作?
我要做的是启动2个线程,一个将共享资源增加1,另一个将减少1,在条件变量和唯一锁的帮助下。我是非常新的使用线程(我昨天开始,我不知道是怎么回事)。在func1和func2中,当注释printf或将其移到count++或count——之上时,程序在第49次迭代时停止(即i=48)。
下面是完整的代码:#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include<condition_variable>
using namespace std;
int count = 0;
mutex lock1;
condition_variable c1;
int resource;
void func1()
{
for(int i = 0; i < 50; i++)
{
// lock1.lock();
unique_lock <mutex> lk1(lock1);
if(count == 0)
{
// cout<<"thread 1 is working on resource: "<<resource<<" i: "<<i<<"n";
printf("nthread 1 is working on resource: %d and i: %d", resource, i);
resource++;
// cout<<"thread 1 work completed, new value: "<<resource<<"n";
printf("nthread 1 work completed, new value: %d and i: %d", resource, i);
c1.notify_one();
lk1.unlock();
// printf("nvalue of count before incr %d", count);
count++;
printf("nvalue of count %d", count);
// cout<<"count while exec for t1: "<<count<<endl;
}
else
{
c1.wait(lk1);
// cout<<"count while waiting for t1: "<<count<<endl;
}
}
}
void func2()
{
for(int i = 0; i < 50; i++)
{
// lock1.lock();
unique_lock <mutex> lk1(lock1);
if(count == 1)
{
// cout<<"thread 2 is working on resource: "<<resource<<" i: "<<i<<"n";
printf("nthread 2 is working on resource: %d and i: %d", resource, i);
resource--;
// cout<<"thread 2 work completed, new value: "<<resource<<"n";
printf("nthread 2 work completed, new value: %d and i: %d", resource, i);
c1.notify_one();
lk1.unlock();
// printf("nvalue of count before decr %d", count);
count--;
printf("nvalue of count %d", count);
// cout<<"count while exec for t2: "<<count<<endl;
}
else
{
c1.wait(lk1);
// cout<<"count while waiting for t2: "<<count<<endl;
}
}
}
int main()
{
auto start = chrono::high_resolution_clock::now();
thread worker1(func1);
thread worker2(func2);
cout<<"nthread started"<<endl;
worker1.join();
worker2.join();
cout<<"nthread completed"<<endl;
auto end = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<chrono::milliseconds>(end - start);
cout<<duration.count();
}
我不知道为什么printf的位置是作为一个枢轴为程序的能力运行我写这段代码只是为了看看为什么程序不能完全执行,方法是在每一步打印count的值,然后程序神奇地完全执行。对不起,如果这个问题是由一些非常微不足道的东西引起的,把它归咎于我的2个神经元,剩下的是做所有的工作(一次只有2个线程lol)。
lk1.unlock();
count++;
两个执行线程都有相同的代码。两个执行线程释放lock1
互斥锁并更新count
,没有适当的同步,没有持有互斥锁。这是未定义的行为。您不能期望从所显示的程序中得到任何特定的结果。