Skip to content

Commit 0a58172

Browse files
Merge pull request #6804 from dok-net/optimistic_yield_recurrency
Fix optimistic_yield to not yield on each call after x µs
2 parents f066ed2 + 5100bee commit 0a58172

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

cores/esp8266/Arduino.h

+1
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ void setup(void);
204204
void loop(void);
205205

206206
void yield(void);
207+
207208
void optimistic_yield(uint32_t interval_us);
208209

209210
#define _PORT_GPIO16 1

cores/esp8266/core_esp8266_main.cpp

+12-7
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ extern "C" {
3737

3838
#define LOOP_TASK_PRIORITY 1
3939
#define LOOP_QUEUE_SIZE 1
40-
#define OPTIMISTIC_YIELD_TIME_US 16000
4140

4241
extern "C" void call_user_start();
4342
extern void loop();
@@ -58,7 +57,7 @@ cont_t* g_pcont __attribute__((section(".noinit")));
5857
static os_event_t s_loop_queue[LOOP_QUEUE_SIZE];
5958

6059
/* Used to implement optimistic_yield */
61-
static uint32_t s_micros_at_task_start;
60+
static uint32_t s_cycles_at_yield_start;
6261

6362
/* For ets_intr_lock_nest / ets_intr_unlock_nest
6463
* Max nesting seen by SDK so far is 2.
@@ -97,6 +96,7 @@ extern "C" bool can_yield() {
9796
static inline void esp_yield_within_cont() __attribute__((always_inline));
9897
static void esp_yield_within_cont() {
9998
cont_yield(g_pcont);
99+
s_cycles_at_yield_start = ESP.getCycleCount();
100100
run_scheduled_recurrent_functions();
101101
}
102102

@@ -125,14 +125,19 @@ extern "C" void __yield() {
125125
extern "C" void yield(void) __attribute__ ((weak, alias("__yield")));
126126

127127
extern "C" void optimistic_yield(uint32_t interval_us) {
128-
if (can_yield() &&
129-
(system_get_time() - s_micros_at_task_start) > interval_us)
128+
const uint32_t intvl_cycles = interval_us *
129+
#if defined(F_CPU)
130+
clockCyclesPerMicrosecond();
131+
#else
132+
ESP.getCpuFreqMHz();
133+
#endif
134+
if ((ESP.getCycleCount() - s_cycles_at_yield_start) > intvl_cycles &&
135+
can_yield())
130136
{
131137
yield();
132138
}
133139
}
134140

135-
136141
// Replace ets_intr_(un)lock with nestable versions
137142
extern "C" void IRAM_ATTR ets_intr_lock() {
138143
if (ets_intr_lock_stack_ptr < ETS_INTR_LOCK_NEST_MAX)
@@ -183,7 +188,7 @@ static void loop_wrapper() {
183188

184189
static void loop_task(os_event_t *events) {
185190
(void) events;
186-
s_micros_at_task_start = system_get_time();
191+
s_cycles_at_yield_start = ESP.getCycleCount();
187192
cont_run(g_pcont, &loop_wrapper);
188193
if (cont_check(g_pcont) != 0) {
189194
panic();
@@ -211,7 +216,7 @@ extern void __unhandled_exception(const char *str);
211216
static void __unhandled_exception_cpp()
212217
{
213218
#ifndef __EXCEPTIONS
214-
abort();
219+
abort();
215220
#else
216221
static bool terminating;
217222
if (terminating)

0 commit comments

Comments
 (0)