C++ 定时互斥如何工作?

C++ 定时互斥如何工作?,c++,pthreads,mutex,C++,Pthreads,Mutex,我只是被困在这段代码中,我假设代码将全局变量“a”锁定30秒,但输出不满足这个假设。有人能帮我弄清楚为什么会发生这种情况吗?另一个问题是,有没有函数可以在程序员指定的特定时间内锁定所需的变量。提前感谢您的考虑 #include <iostream> #include <ctime> #include <pthread.h> #include <time.h> #include <chrono> using namespace std

我只是被困在这段代码中,我假设代码将全局变量“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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
//标准时间间隔:秒间隔(100);
定时互斥测试;
int a=0;
空*写(空*参数)
{
自动启动=标准::时钟::稳定时钟::现在();
测试互斥。尝试锁定直到(开始+标准::时钟::秒(30));
a=2;

cout
std::timed_mutex::try_lock_,直到
返回以下任何一个:

  • true
    当获取互斥时,或
  • false
    如果试图锁定互斥锁超时(等待时间尽可能长)

  • 请注意,这段代码还是有缺陷的,因为它不检查返回值。因此,即使没有获取互斥锁,
    a
    也可以编写。

    出于兴趣,您在询问此问题之前搜索过吗?我似乎清楚地看到了这段代码。