所以我试图制作一个应该死锁的C ++程序。通过下面的代码,我相信它应该可以工作,但不会死锁。我的互斥锁()不能正常工作吗?我的意思是,如果mut2.lock()锁定了关键部分,则它应该解锁,直到正确完成为止,这意味着funcA不应该运行,或者至少等到mut2.unlock()为止,因为它们都使用了资源rs2?我为什么不能使程序死锁?

#include <iostream>
#include <thread>
#include <mutex>
#include <pthread.h>
#include <cstdio>   // getchar
#include <thread>   // this_thread, yield
#include <future>   // async
#include <chrono>   // seconds
#include <unistd.h>
using namespace std;
mutex mut1, mut2, mut3;
int rs1=1; int rs2 = 2; int rs3=3;
int MAX = 20;

void funcA(){

    mut1.lock();
    cout<<"mut1 lock for thread A\n";
    for(int i=0; i<MAX; i++){
        rs2 = i;
    cout<<"[Aloop]rs1: "<<rs1<<" rs2: "<<rs2<<" rs3: "<<rs3<<" i:"<<i << endl;
    }
    rs1 = rs2;
    cout<<"[A]rs1: "<<rs1<<" rs2: "<<rs2<<" rs3: "<<rs3 << endl;
    mut1.unlock();
    cout<<"mut1 unlock for thread A\n";
}
void funcB(){

    mut2.lock();
    cout<<"mut2 lock for thread B\n";
    rs3 = rs1 + rs2;
    cout<<"[B]rs3: "<<rs3 << " rs1: "<<rs1 << " rs2: "<<rs2 <<endl;
    sleep(50);
    mut2.unlock();
    cout<<"mut2 unlock for thread B\n";
}


int main(){
    thread tA(funcA);
    thread tB(funcB);

    tA.join();
    tB.join();

return 0;
}

//Here is my makefile
#Makefile project 2

project2: project2.o
    g++ -std=c++11 -pthread -o project2 project2.o
project2.o: project2.cpp project2.h
    g++ -std=c++11 -Wall -pthread -c project2.cpp
    //Below is my output



  线程B的mut2锁
  
  [B] rs3:3 rs1:1 rs2:99
  
  线程A的mut1锁
  
  [Aloop] rs1:1 rs2:0 rs3:3 i:0
  
  [Aloop] rs1:1 rs2:1 rs3:3 i:1
  
  [Aloop] rs1:1 rs2:2 rs3:3 i:2
  
  [Aloop] rs1:1 rs2:3 rs3:3 i:3
  
  [Aloop] rs1:1 rs2:5 rs3:3 i:5
  
  [Aloop] rs1:1 rs2:6 rs3:3 i:6
  
  [Aloop] rs1:1 rs2:7 rs3:3 i:7
  
  [Aloop] rs1:1 rs2:8 rs3:3 i:8
  
  [Aloop] rs1:1 rs2:9 rs3:3 i:9
  
  [Aloop] rs1:1 rs2:10 rs3:3 i:10
  
  [Aloop] rs1:1 rs2:11 rs3:3 i:11
  
  [Aloop] rs1:1 rs2:12 rs3:3 i:12
  
  [Aloop] rs1:1 rs2:13 rs3:3 i:13
  
  [Aloop] rs1:1 rs2:14 rs3:3 i:14
  
  [Aloop] rs1:1 rs2:15 rs3:3 i:15
  
  [Aloop] rs1:1 rs2:16 rs3:3 i:16
  
  [Aloop] rs1:1 rs2:17 rs3:3 i:17
  
  [Aloop] rs1:1 rs2:18 rs3:3 i:18
  
  [Aloop] rs1:1 rs2:19 rs3:3 i:19
  
  [A] rs1:19 rs2:19 rs3:3
  
  线程A的mut1解锁
  
  线程B的mut2解锁

最佳答案

这两个线程试图锁定不同的互斥锁,因此它们无法死锁。

尽管可以用多种不同方式想象线程死锁,但是除非一个线程试图获取另一个线程持有的互斥锁,否则不会发生带有互斥锁的死锁。 (当然,其他事情也需要发生。如果发生这种情况,它将仅等待另一个线程释放互斥量而不是死锁。)

10-06 03:04