0

This is my test program.I use g++ to compile code and expect it to block when the function void foo() is executed, but it don't block . I don't know what is wrong? I use gcc to compile code, it can block. who can tell me difference.

#include <pthread.h>
#include <iostream>
using namespace std;
static pthread_mutex_t mutex;
void foo()
{
    pthread_mutex_lock(&mutex);
    cout<<"this is foo()"<<endl;
    pthread_mutex_unlock(&mutex);
}

void bar()
{
    pthread_mutex_lock(&mutex);
    cout<<"this is bar()"<<endl;
    foo();
    pthread_mutex_unlock(&mutex);
}

  int main()
 {
    pthread_mutex_init(&mutex, NULL);
    bar();
    return 0;
 }

exepect output

this is bar()

actual output:

this is bar()

this is foo()

Community
  • 1
  • 1
PengWin
  • 9
  • 4
  • Have you checked your mutex type to determine whether it is `PTHREAD_MUTEX_RECURSIVE` or `PTHREAD_MUTEX_ERRORCHECK` (related, since you're outright-ignoring return values) ? (vs. `PTHREAD_MUTEX_NORMAL`, which you appear to be expecting). – WhozCraig May 31 '16 at 16:04
  • 1
    [Undefined Behavior](http://stackoverflow.com/questions/11173532/why-is-locking-a-stdmutex-twice-undefined-behaviour?rq=1)? – Bo Persson May 31 '16 at 16:04
  • Actually both mingw and coliru (gcc) shows for me only "this is bar()" – marcinj May 31 '16 at 18:36
  • yes, I have used `gcc` compiled the program. it showed "this is bar()". Howerver, when I use `g++`, it shows for me "this is bar() this is foo()" – PengWin Jun 01 '16 at 02:34
  • @SergeyA I think we need a pthread mutex dup, not a `std::mutex` one... – T.C. Jun 01 '16 at 04:33
  • @T.C. I have resolve it. i forget `-lpthread` when use `g++` to compile code – PengWin Jun 01 '16 at 04:39
  • @WhozCraig ,I get it, i forget `-lpthread` when use`g++` to compile code – PengWin Jun 01 '16 at 04:41
  • @marcinj,you are right. I use `g++ -o test -c Mutex.cc` to get executive program. I forget `-lpthread` that is reason of wrong. – PengWin Jun 01 '16 at 04:45
  • @T.C., you are certainly correct. However, I do not think it matters now. – SergeyA Jun 01 '16 at 13:01

0 Answers0