pthread mutex not working correctly

前端 未结 2 849
夕颜
夕颜 2020-12-06 21:33

I am currently learning C from MIT\'s Open Courseware course called Practical Programming in C. In discussing race conditions in multithreading, the lecture notes contained

相关标签:
2条回答
  • 2020-12-06 22:03

    The reason why it works with linux is, because under linux :

    #define PTHREAD_MUTEX_INITIALIZER { { 0, 0, 0, 0, 0, { 0 } } }
    

    which is exactly how the mutex is initialized anyway, since it is a .bss-variable.

    Under MacOSX, it is some other magic value:

    #define PTHREAD_MUTEX_INITIALIZER {_PTHREAD_MUTEX_SIG_init, {0}}
    #define _PTHREAD_MUTEX_SIG_init     0x32AAABA7
    

    so it indeed has to be initialized to have it working correctly.

    0 讨论(0)
  • 2020-12-06 22:13

    You didn't initialize the mutex. You can either do this:

    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    

    or in the main function, do this:

    if ( pthread_mutex_init( &mutex, NULL) != 0 )
        printf( "mutex init failed\n" );
    
    0 讨论(0)
提交回复
热议问题