pthread_cond_wait执行失败

2024-05-07 05:48
文章标签 执行 失败 wait pthread cond

本文主要是介绍pthread_cond_wait执行失败,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Printf("execute result:%d",pthread_cond_wait(&reply_cond, &reply_mutex));

执行没有返回结果,日志也没有打印

查询linux doc查到如下结果:

Description

The pthread_cond_timedwait() and pthread_cond_wait() functions shall block on a condition variable. They shall be called withmutex locked by the calling thread or undefined behavior results.

These functions atomically release mutex and cause the calling thread to block on the condition variablecond; atomically here means "atomically with respect to access by another thread to the mutex and then the condition variable". That is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call topthread_cond_broadcast() orpthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked.

Upon successful return, the mutex shall have been locked and shall be owned by the calling thread.

When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from thepthread_cond_timedwait() orpthread_cond_wait() functions may occur. Since the return frompthread_cond_timedwait() orpthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

The effect of using more than one mutex for concurrent pthread_cond_timedwait() orpthread_cond_wait() operations on the same condition variable is undefined; that is, a condition variable becomes bound to a unique mutex when a thread waits on the condition variable, and this (dynamic) binding shall end when the wait returns.

A condition wait (whether timed or not) is a cancellation point. When the cancelability enable state of a thread is set to PTHREAD_CANCEL_DEFERRED, a side effect of acting upon a cancellation request while in a condition wait is that the mutex is (in effect) re-acquired before calling the first cancellation cleanup handler. The effect is as if the thread were unblocked, allowed to execute up to the point of returning from the call topthread_cond_timedwait() orpthread_cond_wait(), but at that point notices the cancellation request and instead of returning to the caller ofpthread_cond_timedwait() orpthread_cond_wait(), starts the thread cancellation activities, which includes calling cancellation cleanup handlers.

A thread that has been unblocked because it has been canceled while blocked in a call topthread_cond_timedwait() orpthread_cond_wait() shall not consume any condition signal that may be directed concurrently at the condition variable if there are other threads blocked on the condition variable.

The pthread_cond_timedwait() function shall be equivalent to pthread_cond_wait(), except that an error is returned if the absolute time specified byabstime passes (that is, system time equals or exceedsabstime) before the conditioncond is signaled or broadcasted, or if the absolute time specified byabstime has already been passed at the time of the call.

If the Clock Selection option is supported, the condition variable shall have a clock attribute which specifies the clock that shall be used to measure the time specified by theabstime argument. When such timeouts occur,pthread_cond_timedwait() shall nonetheless release and re-acquire the mutex referenced bymutex. Thepthread_cond_timedwait() function is also a cancellation point.

If a signal is delivered to a thread waiting for a condition variable, upon return from the signal handler the thread resumes waiting for the condition variable as if it was not interrupted, or it shall return zero due to spurious wakeup.

Return Value

Except in the case of [ETIMEDOUT], all these error checks shall act as if they were performed immediately at the beginning of processing for the function and shall cause an error return, in effect, prior to modifying the state of the mutex specified bymutex or the condition variable specified by cond.

Upon successful completion, a value of zero shall be returned; otherwise, an error number shall be returned to indicate the error.

Errors

The pthread_cond_timedwait() function shall fail if:

ETIMEDOUT
The time specified by abstime to pthread_cond_timedwait() has passed.

The pthread_cond_timedwait() and pthread_cond_wait() functions may fail if:

EINVAL
The value specified by cond, mutex, or abstime is invalid.
EINVAL
Different mutexes were supplied for concurrent pthread_cond_timedwait() or pthread_cond_wait() operations on the same condition variable.
EPERM
The mutex was not owned by the current thread at the time of the call.

These functions shall not return an error code of [EINTR].

查询源码:

pthread.h

int pthread_cond_broadcast(pthread_cond_t*) __nonnull((1));
int pthread_cond_destroy(pthread_cond_t*) __nonnull((1));
int pthread_cond_init(pthread_cond_t*, const pthread_condattr_t*) __nonnull((1));
int pthread_cond_signal(pthread_cond_t*) __nonnull((1));
int pthread_cond_timedwait(pthread_cond_t*, pthread_mutex_t*, const struct timespec*) __nonnull((1, 2, 3));
int pthread_cond_wait(pthread_cond_t*, pthread_mutex_t*) __nonnull((1, 2));

pthread_cond.cpp
int pthread_cond_broadcast(pthread_cond_t* cond) {return __pthread_cond_pulse(cond, INT_MAX);
}int pthread_cond_signal(pthread_cond_t* cond) {return __pthread_cond_pulse(cond, 1);
}int pthread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex) {return __pthread_cond_timedwait(cond, mutex, NULL, COND_GET_CLOCK(cond->value));
}int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t * mutex, const timespec *abstime) {return __pthread_cond_timedwait(cond, mutex, abstime, COND_GET_CLOCK(cond->value));
}

__LIBC_HIDDEN__
int __pthread_cond_timedwait(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* abstime, clockid_t clock) {timespec ts;timespec* tsp;if (abstime != NULL) {if (__timespec_from_absolute(&ts, abstime, clock) < 0) {//注释1return ETIMEDOUT;}tsp = &ts;} else {tsp = NULL;}return __pthread_cond_timedwait_relative(cond, mutex, tsp);
}

__LIBC_HIDDEN__
int __pthread_cond_timedwait_relative(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* reltime) {int old_value = cond->value;pthread_mutex_unlock(mutex);int status = __futex_wait_ex(&cond->value, COND_IS_SHARED(cond->value), old_value, reltime);pthread_mutex_lock(mutex);if (status == -ETIMEDOUT) {return ETIMEDOUT;}return 0;
}
没有返回值的问题应该出在这里,可能是:
1.pthread_mutex_unlock(mutex);处,解锁没有成功,导致别的线程无法获得锁,刚开始在我的问题代码中pthread_cond_signal前确实无法获得锁;
2.__futex_wait_ex一直没有接收到条件变量的通知,一直在等待;
3.pthread_mutex_lock(mutex);处,别的线程已经锁住,无法继续执行。
在我的问题代码去掉获锁解锁后,pthread_cond_signal后pthread_cond_wait执行不成功,2和3的可能也是存在的。

bionic_futex.h
static inline int __futex_wake_ex(volatile void* ftx, bool shared, int count) {return __futex(ftx, shared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, count, NULL);
}
static inline __always_inline int __futex(volatile void* ftx, int op, int value, const struct timespec* timeout) {// Our generated syscall assembler sets errno, but our callers (pthread functions) don't want to.int saved_errno = errno;int result = syscall(__NR_futex, ftx, op, value, timeout);if (__predict_false(result == -1)) {//注释2result = -errno;errno = saved_errno;}return result;
}
syscall.h
#ifndef _SYS_SYSCALL_H_
#define _SYS_SYSCALL_H_#include <errno.h>
#include <sys/cdefs.h>
#include <sys/types.h>
#include <asm/unistd.h>#include <sys/glibc-syscalls.h> /* glibc-compatible SYS_* aliases for our __NR_* names. */__BEGIN_DECLSlong syscall(long number, ...);__END_DECLS#endif

syscall是间接系统调用
查询linux doc:

NAME  top

       syscall - indirect system call

SYNOPSIS        top

       #define _GNU_SOURCE         /* See feature_test_macros(7) */#include <unistd.h>#include <sys/syscall.h>   /* For SYS_xxx definitions */long syscall(long number, ...);

DESCRIPTION        top

       syscall() is a small library function that invokes the system callwhose assembly language interface has the specified number with thespecified arguments.  Employing syscall() is useful, for example,when invoking a system call that has no wrapper function in the Clibrary.syscall() saves CPU registers before making the system call, restoresthe registers upon return from the system call, and stores any errorcode returned by the system call in errno(3) if an error occurs.Symbolic constants for system call numbers can be found in the headerfile <sys/syscall.h>.

RETURN VALUE        top

       The return value is defined by the system call being invoked.  Ingeneral, a 0 return value indicates success.  A -1 return valueindicates an error, and an error code is stored in errno.
syscall() 执行一个系统调用,根据指定的参数number和所有系统调用的汇编语言接口来确定调用哪个系统调用。
系统调用所使用的符号常量可以在头文件<sys/syscall.h>里面找到。

syscall(__NR_futex, ftx, op, value, timeout)中的__NR_futex可以在android5.1\bionic\libc\include\sys\glibc-syscalls.h中找到:
#define SYS_futex __NR_futex
在不同的平台值不同,例如在android5.1\bionic\libc\kernel\uapi\asm-x86\asm\unistd_64.h中:
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define __NR_futex 202
#define __NR_sched_setaffinity 203
#define __NR_sched_getaffinity 204
#define __NR_set_thread_area 205




注释1:__timespec_from_absolute在pthread_internals.cpp定义

// Initialize 'ts' with the difference between 'abstime' and the current time
// according to 'clock'. Returns -1 if abstime already expired, or 0 otherwise.
int __timespec_from_absolute(timespec* ts, const timespec* abstime, clockid_t clock) {clock_gettime(clock, ts);ts->tv_sec  = abstime->tv_sec - ts->tv_sec;ts->tv_nsec = abstime->tv_nsec - ts->tv_nsec;if (ts->tv_nsec < 0) {ts->tv_sec--;ts->tv_nsec += 1000000000;}if ((ts->tv_nsec < 0) || (ts->tv_sec < 0)) {return -1;}return 0;
}

注释2:__predict_false在cdefs.h定义

#if __GNUC_PREREQ(2, 96)
#define __predict_true(exp) __builtin_expect((exp) != 0, 1)
#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
#else
#define __predict_true(exp) (exp)
#define __predict_false(exp) (exp)
#endif



这篇关于pthread_cond_wait执行失败的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/966491

相关文章

Spring Boot 整合 ShedLock 处理定时任务重复执行的问题小结

《SpringBoot整合ShedLock处理定时任务重复执行的问题小结》ShedLock是解决分布式系统中定时任务重复执行问题的Java库,通过在数据库中加锁,确保只有一个节点在指定时间执行... 目录前言什么是 ShedLock?ShedLock 的工作原理:定时任务重复执行China编程的问题使用 Shed

详解如何在React中执行条件渲染

《详解如何在React中执行条件渲染》在现代Web开发中,React作为一种流行的JavaScript库,为开发者提供了一种高效构建用户界面的方式,条件渲染是React中的一个关键概念,本文将深入探讨... 目录引言什么是条件渲染?基础示例使用逻辑与运算符(&&)使用条件语句列表中的条件渲染总结引言在现代

Xshell远程连接失败以及解决方案

《Xshell远程连接失败以及解决方案》本文介绍了在Windows11家庭版和CentOS系统中解决Xshell无法连接远程服务器问题的步骤,在Windows11家庭版中,需要通过设置添加SSH功能并... 目录一.问题描述二.原因分析及解决办法2.1添加ssh功能2.2 在Windows中开启ssh服务2

Redis连接失败:客户端IP不在白名单中的问题分析与解决方案

《Redis连接失败:客户端IP不在白名单中的问题分析与解决方案》在现代分布式系统中,Redis作为一种高性能的内存数据库,被广泛应用于缓存、消息队列、会话存储等场景,然而,在实际使用过程中,我们可能... 目录一、问题背景二、错误分析1. 错误信息解读2. 根本原因三、解决方案1. 将客户端IP添加到Re

如何使用 Bash 脚本中的time命令来统计命令执行时间(中英双语)

《如何使用Bash脚本中的time命令来统计命令执行时间(中英双语)》本文介绍了如何在Bash脚本中使用`time`命令来测量命令执行时间,包括`real`、`user`和`sys`三个时间指标,... 使用 Bash 脚本中的 time 命令来统计命令执行时间在日常的开发和运维过程中,性能监控和优化是不

C#如何优雅地取消进程的执行之Cancellation详解

《C#如何优雅地取消进程的执行之Cancellation详解》本文介绍了.NET框架中的取消协作模型,包括CancellationToken的使用、取消请求的发送和接收、以及如何处理取消事件... 目录概述与取消线程相关的类型代码举例操作取消vs对象取消监听并响应取消请求轮询监听通过回调注册进行监听使用Wa

PHP执行php.exe -v命令报错的解决方案

《PHP执行php.exe-v命令报错的解决方案》:本文主要介绍PHP执行php.exe-v命令报错的解决方案,文中通过图文讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下... 目录执行phpandroid.exe -v命令报错解决方案执行php.exe -v命令报错-PHP War

Oracle数据库执行计划的查看与分析技巧

《Oracle数据库执行计划的查看与分析技巧》在Oracle数据库中,执行计划能够帮助我们深入了解SQL语句在数据库内部的执行细节,进而优化查询性能、提升系统效率,执行计划是Oracle数据库优化器为... 目录一、什么是执行计划二、查看执行计划的方法(一)使用 EXPLAIN PLAN 命令(二)通过 S

maven 编译构建可以执行的jar包

💝💝💝欢迎莅临我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。 推荐:「stormsha的主页」👈,「stormsha的知识库」👈持续学习,不断总结,共同进步,为了踏实,做好当下事儿~ 专栏导航 Python系列: Python面试题合集,剑指大厂Git系列: Git操作技巧GO

ORACLE 11g 创建数据库时 Enterprise Manager配置失败的解决办法 无法打开OEM的解决办法

在win7 64位系统下安装oracle11g,在使用Database configuration Assistant创建数据库时,在创建到85%的时候报错,错误如下: 解决办法: 在listener.ora中增加对BlueAeri-PC或ip地址的侦听,具体步骤如下: 1.启动Net Manager,在“监听程序”--Listener下添加一个地址,主机名写计