pthread_mutex_lock不是instante ......?

时间:2017-07-29 19:13:30

标签: multithreading pthreads mutex

人。我试图使用互斥量作为原子变量的替代品,但是已经重新演示了,似乎互斥体不是instante,因为" num"还有时间改变一半,使if条件成立。 这样做是不是像我那样工作,或者我只是这样做:() Comente请...谢谢:D

yaw, pitch and roll

结果:

#include <iostream>
#include <pthread.h>
#include <mutex>
using namespace std;

 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int num = 450;

void* print1 (void* e){
    while(1){
         if(num != 450 && num != 201 ){
        cout << "num-> "<<num<<endl;
        }

        pthread_mutex_lock(&mutex);
        Sleep(0.5);
        num = 450;
        pthread_mutex_unlock(&mutex);
    }

}

void* print2 (void* e){
    while(1){
        if(num != 450 && num != 201 ){
        cout << "num-> "<<num<<endl;
        }

        pthread_mutex_lock(&mutex);
        Sleep(0.5);
        num = 201;
        pthread_mutex_unlock(&mutex);
    }

}


int main(){

    pthread_t* threads1;
    threads1 = new pthread_t;

     pthread_t* threads2;
    threads2 = new pthread_t;
//-------------------------------------
    pthread_create(threads1,NULL,print1,(void*)NULL);
    pthread_create(threads2,NULL,print2,(void*)NULL);
    pthread_join(*threads1,(void**)NULL);
    pthread_join(*threads2,(void**)NULL);

return false;
}

我在期待:

num-> 450
num-> 450
num-> 450
num-> 450
...

1 个答案:

答案 0 :(得分:2)

您的代码不会将对共享num变量的读访问权与对同一变量的写访问权同步。使用-fsanitize=thread进行编译时,这一点清晰可见:

WARNING: ThreadSanitizer: data race (pid=3082)
  Write of size 4 at 0x0000006020d0 by thread T1 (mutexes: write M9):
    #0 print1(void*) test.cc:19 (test+0x000000400df0)
    #1 <null> <null> (libtsan.so.0+0x000000024459)

  Previous read of size 4 at 0x0000006020d0 by thread T2:
    #0 print2(void*) test.cc:27 (test+0x000000400e3f)
    #1 <null> <null> (libtsan.so.0+0x000000024459)

读访问也需要某种形式的同步,而不仅仅是写访问。否则,您甚至可能无法观察更新或查看不一致的数据。细节是C++ memory model的结果。