pthread_mutex_trylock? Windows中的pthreads

时间:2014-04-21 10:18:31

标签: c++ multithreading pthreads

/ // / / / / / / // / / ///// / // / / / / / / / / / // / *

pthread_mutex_t stop = PTHREAD_MUTEX_INITIALIZER;
int a = 1;

void* decrement(void* arg)
{ 
    pthread_mutex_trylock(&stop);
    if(a > 0) { a--; } 
    cout << "Esecuzione thread tid" << endl;
    pthread_mutex_unlock(&stop);
    pthread_exit(NULL);
}

int main()
{
    pthread_t tid;

    pthread_attr_t tattr;
    pthread_attr_init(&tattr);
    pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_DETACHED);

    pthread_create(&tid, &tattr, decrement, NULL);

    pthread_mutex_lock(&stop);
    if(a > 0) { a--; } 
    cout << "Esecuzione thread main" << endl;

    cout << a << endl;

    pthread_exit(NULL);
    return 0;
}

为什么分离到主线程的线程继续执行而不是用EBUSY返回给调用者?

1 个答案:

答案 0 :(得分:1)

您的问题中没有特定于Windows的内容。你实际上误解了pthread_mutex_trylock()的工作原理。

  

pthread_mutex_trylock()函数应等效于pthread_mutex_lock(),但如果互斥引用的互斥对象当前被锁定(由任何线程,包括当前线程),则调用应立即返回。登记/>   ...
  如果出现以下情况,pthread_mutex_trylock()功能将失败:
  [EBUSY]
  无法获取互斥锁,因为它已被锁定。

不是decrement线程而是pthread_mutex_trylock()返回(可能返回)EBUSY(你没有检查......)

顺便说一下,decrement线程也可以在pthread_mutex_lock(&stop)线程中的main()之前执行它的执行。这完全是不确定的。