gpt4 book ai didi

c++ - pthread_mutex_trylock? Windows 中的线程

转载 作者:行者123 更新时间:2023-11-28 06:55:50 25 4
gpt4 key购买 nike

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

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() 的工作原理。

The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately.
...
The pthread_mutex_trylock() function shall fail if:
[EBUSY]
The mutex could not be acquired because it was already locked.

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

顺便说一句,decrement 线程也有可能比 main() 中的 pthread_mutex_lock(&stop) 更早完成执行线。这完全是不确定的。

关于c++ - pthread_mutex_trylock? Windows 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23195378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com