两个线程叫提出打印0-100的数字

先上代码:

#include <thread>
#include <condition_variable>
#include <mutex>
#include <iostream>
using namespace std;

int main() {
    mutex mtx;
    condition_variable cv;
    int i = 0;
    int MAXX = 100;
    bool turn = false;  // false → p1’s turn; true → p2’s turn

    thread p1([&] {
        while (1) {
            unique_lock<mutex> lock(mtx);
            cv.wait(lock, [&] { return turn == false; });
            turn = true;        // hand over to p2
            if (i > MAXX) {
                cv.notify_one();  
                cout << "thread 1 break" << endl;
                break;
            }
            cout << "thread 1 sees i = " << i << "\n";
            ++i;

            lock.unlock();
            cv.notify_one();
        }; 
    });

	thread p2([&] {
		while (1) {
			unique_lock<mutex> lock(mtx);
			cv.wait(lock, [&] { return turn == true; });
            turn = false;        // hand over to p1
            if (i > MAXX) {
                cv.notify_one();
                cout << "thread 2 break" << endl;
                break;
            }
			cout << "thread 2 sees i = " << i << "\n";
			++i;
			turn = false;       // back to p1 (if you did more rounds)
			lock.unlock();
			cv.notify_one();

		};
	});

    p1.join();
    p2.join();

    cout << "final i = " << i << "\n";
    return 0;
}

代码解释:

  • 代码中声明了互斥锁mtx,条件变量cv,并通过i进行计数,MAXX限制最大的打印范围,并设置turn为false;
  • 随后创建了两个线程,线程内都是while(1)死循环。
  • 线程p1会在turn等于false的时候停止等待,抢占mtx,随后把turn设置为ture;并对i的数值做出判断,如果大于MAXX则中断,并通知其他的线程;如果小于MAXX则会打印,并i++;随后解锁,并通知其他的线程。
  • 因为线程p1结束之后turn为true,此时p2结束wait,随后把turn设置为flase;并对i的数值做出判断,如果大于MAXX则中断,并通知其他的线程;如果小于MAXX则会打印,并i++;随后解锁,并通知其他的线程。
  • 此时p1结束wait等待的条件又得到了满足。
  • 中间依次往复,p1输出偶数,p2输出奇数。
  • p1结束wait,此时i>MAXX;此时设置turn为ture;通知其他线程,并中断循环。p1线程结束。
  • p2结束wait,此时i>MAXX;此时设置turn为false;通知其他线程,并中断循环。p2线程结束。
    运行结果如下:

    注意:
    必须在if(i>MAXX) ... then break前面就设置好turn的反转,否则另外一个永远得不到wait结束的条件,会导致死锁。
posted @ 2025-05-23 20:43  紫川Bin  阅读(13)  评论(0)    收藏  举报