pthread_mutex_trylock? pthreads in Windows

pthread_mutex_trylock? pthreads in Windows

本文关键字:in Windows pthreads trylock mutex pthread      更新时间:2023-10-16

////////////////////////////<<em>/\/>

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返回到调用方?

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

  • http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html

pthread_mutex_trylock()函数应等效于pthread_mutex_lock(),但如果互斥对象引用的互斥对象当前被锁定(被任何线程锁定,包括当前线程),则调用应立即返回

如果出现以下情况,pthread_mutex_trylock()功能将失败:
[EBUSY]
无法获取互斥对象,因为它已被锁定。

返回(可能返回)EBUSY(您没有检查…)的不是decrement线程,而是pthread_mutex_trylock()

顺便说一下,decrement线程也可以在main()线程中比pthread_mutex_lock(&stop)更早地定义其执行。这是完全无法确定的。