- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
/////////////////////////////////*
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 topthread_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.
...
Thepthread_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/
我花了一周的时间来修复一个程序,一开始我得到了SIGBUS,但经过多次尝试后程序仍然得到了SIGSEGV段错误,在下面我发布了段错误日志+源代码。如果专家帮助我修复此段错误错误,我将非常感激。任何建议
我正在使用 pthread_mutex_trylock 将互斥锁锁定在一个结构上,以便它只能在给定时间由单个线程访问/修改。如果互斥体已经被锁定,我只是从例程返回而不是排队/阻塞。 这是我的代码的基本
在我的代码中,我使用 pthread_mutx_trylock() 来检查线程 1 是否已完成他的任务工作并释放互斥锁吗?请让我知道它是否有效? 在线程 1 中: pthread_mutex
/////////////////////////////////* pthread_mutex_t stop = PTHREAD_MUTEX_INITIALIZER; int a = 1; void
我正在学习在 Linux 编程中使用互斥量。我遇到了 trylock 函数,它首先检查互斥量是否可用,否则将其锁定,然后返回。 现在我的问题是: 调用trylock时,是否在未执行临界区的情况下到达函
最近看了memcached的源码,在文件 memcached.h 中。我找到了这段代码: static inline int mutex_lock(pthread_mutex_t *mutex) {
我有以下测试程序。 #include #include using namespace std; pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIA
pthread_mutex_trylock 检测死锁,不阻塞,那你为什么“需要” pthread_mutex_lock? 也许当你故意想让线程阻塞?但那样的话可能会导致死锁? 最佳答案 pthread
一旦线程被取消,就需要解锁互斥体,以避免死锁。所以我设计了以下方法: // file_a.c pthread_attr_t attr; ... rc2 = pthread_attr_init(&att
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 要求提供代码的问题必须表现出对所解决问题的最低限度理解。包括尝试过的解决方案、为什么它们不起作用,以及预
这是对 this 的跟进问题。 在该代码中,当我不使用 fflush(stdout) 时,当我保持 sleep(1) 时,输出不会刷新到屏幕上。 #define S sleep(0) void* xT
我是一名优秀的程序员,十分优秀!