Search code examples
c++multithreadingdeadlock

What should I modify to prevent deadlock on c++ thread


Here is my source code:

#include "stdio.h"
#include <stdlib.h>
#include <string.h>
#include "thread"
#include "mutex"

int count0=0 ,count1 =0;
std::mutex main_thread;
std::unique_lock<std::mutex> lck(main_thread, std::defer_lock);

void Function00(long millisecond){

    while (true){

        lck.lock();
        count1++;
        printf("count0:%d count1:%d \n",count0,count1);
        lck.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(millisecond));

    }
}

void Function01(){

    std::thread th(Function00, 1000);//count per 1 s

    do{
        lck.lock();
        count0++;
        lck.unlock();
        std::this_thread::sleep_for(std::chrono::milliseconds(500));//count per 0.5 s
    } while (1);

}



int main(int argc, char *argv[])
{
    Function01();


    return 0;
}

I then use the command to build my .o file:

g++ -std=c++11 -pthread testa.cpp -o a.o

However, it shows the error:

terminate called after throwing an instance of 'std::system_error'
  what():  Resource deadlock avoided
Aborted

I feel confuse and no idea to solve it, so i try in Microsoft VS2013, and it runs with no error... I feel confuse to it. Is it the problem in linux? What should i modify to prevent the deadlock?


Solution

  • unique_lock cannot be locked twice, if you want to lock a mutex on two threads so that one of them will block, you need to use two unique_locks.

    void Function00(long millisecond){
    
        while (true){
    
            {
                std::unique_lock<std::mutex> lck(main_thread);
                count1++;
                printf("count0:%d count1:%d \n",count0,count1);
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(millisecond));
    
        }
    }
    
    void Function01(){
    
        std::thread th(Function00, 1000);//count per 1 s
    
        do{
            {
                std::unique_lock<std::mutex> lck(main_thread);
                count0++;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(500));//count per 0.5 s
        } while (1);
    
    }