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

相关文章

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

解密SQL查询语句执行的过程

《解密SQL查询语句执行的过程》文章讲解了SQL语句的执行流程,涵盖解析、优化、执行三个核心阶段,并介绍执行计划查看方法EXPLAIN,同时提出性能优化技巧如合理使用索引、避免SELECT*、JOIN... 目录1. SQL语句的基本结构2. SQL语句的执行过程3. SQL语句的执行计划4. 常见的性能优

Spring Bean初始化及@PostConstruc执行顺序示例详解

《SpringBean初始化及@PostConstruc执行顺序示例详解》本文给大家介绍SpringBean初始化及@PostConstruc执行顺序,本文通过实例代码给大家介绍的非常详细,对大家的... 目录1. Bean初始化执行顺序2. 成员变量初始化顺序2.1 普通Java类(非Spring环境)(

Spring Boot 中的默认异常处理机制及执行流程

《SpringBoot中的默认异常处理机制及执行流程》SpringBoot内置BasicErrorController,自动处理异常并生成HTML/JSON响应,支持自定义错误路径、配置及扩展,如... 目录Spring Boot 异常处理机制详解默认错误页面功能自动异常转换机制错误属性配置选项默认错误处理

如何在Java Spring实现异步执行(详细篇)

《如何在JavaSpring实现异步执行(详细篇)》Spring框架通过@Async、Executor等实现异步执行,提升系统性能与响应速度,支持自定义线程池管理并发,本文给大家介绍如何在Sprin... 目录前言1. 使用 @Async 实现异步执行1.1 启用异步执行支持1.2 创建异步方法1.3 调用

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

SpringBoot整合Dubbo+ZK注册失败的坑及解决

《SpringBoot整合Dubbo+ZK注册失败的坑及解决》使用Dubbo框架时,需在公共pom添加依赖,启动类加@EnableDubbo,实现类用@DubboService替代@Service,配... 目录1.先看下公共的pom(maven创建的pom工程)2.启动类上加@EnableDubbo3.实

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

解决mysql插入数据锁等待超时报错:Lock wait timeout exceeded;try restarting transaction

《解决mysql插入数据锁等待超时报错:Lockwaittimeoutexceeded;tryrestartingtransaction》:本文主要介绍解决mysql插入数据锁等待超时报... 目录报错信息解决办法1、数据库中执行如下sql2、再到 INNODB_TRX 事务表中查看总结报错信息Lock