Timed_mutex如何运作?

时间:2014-04-17 10:26:41

标签: c++ pthreads mutex

我只是陷入这段代码中,我认为代码锁定了全局变量" a" 30秒,但输出不满足这个假设。任何人都可以帮我弄清楚为什么会发生这种情况,而另一个问题是,是否有任何函数可以锁定特定时间内所需的变量,由程序员指定。谢谢您提前考虑。

#include <iostream>
#include <ctime>
#include <pthread.h>
#include <time.h>
#include <chrono>


using namespace std;
// std::chrono::seconds interval(100);


timed_mutex test_mutex;
int a = 0;

void * write(void * args)
{
    auto start=std::chrono::steady_clock::now();
    test_mutex.try_lock_until(start+std::chrono::seconds(30));
    a = 2;
    cout << "Here is place #" << a << endl;
    test_mutex.unlock();
    pthread_exit(NULL);
}



int main()
{
    auto start=std::chrono::steady_clock::now();
    pthread_t check;
    pthread_create(&check, NULL, &write, NULL);
    test_mutex.try_lock_until(start+std::chrono::seconds(30));
    a = 1;
    cout << "Here is place #" << a << endl;
    test_mutex.unlock();
    pthread_join(check, NULL);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

std::timed_mutex::try_lock_until返回:

    获取互斥锁时
  1. true,或
  2. false如果超时(等待允许)试图锁定互斥锁
  3. 请注意,此代码无论如何都是错误的,因为它不会检查返回值。因此,即使互斥锁获取,也可以编写a