pthread_mutex_trylock? pthreads in Windows
pthread_mutex_trylock? pthreads in Windows
/////////////////////
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)
更早地定义其执行。这是完全无法确定的。
相关文章:
- std::async from std::async in windows xp
- 如何在 google test in windows 中管理断言
- 在Windows Visual Studio中实现<netinet/in.h>
- C++ - 程序接收信号SIGSEGV,分段错误.In msvcrt!memcpy () (C:\Windows\S
- 使用 new in C++(在 Windows 上)分配大于 2GB 的单个对象
- pthread_cond_timedwait() in Windows
- TLS with http_listener in Microsoft cpprestsdk on Windows
- Windows 10 环境中的"This version of XAudio2 is available only in Windows 8"错误
- QT c++ "Windows.h no such a file or dictionary in main.ccp"
- QB,如何在Windows上配置.h.in文件
- No FileIO in Windows Phone?
- OLEUnInitialize() in windows 7
- Sleep() in Windows 消息循环
- Cython in Windows 64 with GSL
- gethostname() in windows
- Windows Runtime activatable class in Windows 10
- openCV in Windows mobile
- ShellExecute in Windows Embedded
- pthread_mutex_trylock? pthreads in Windows
- Issue with eclipse juno for c,c++ in windows