Add definition for threaded work queue

This commit is contained in:
johnny9 2023-04-26 09:00:48 -04:00
parent 9c109e7553
commit d34fcfabff
3 changed files with 88 additions and 0 deletions

View File

@ -21,4 +21,5 @@ idf_component_register(SRCS
"pretty.c"
"tcp_client.c"
"stratum_api.c"
"work_queue.c"
INCLUDE_DIRS ".")

47
main/work_queue.c Normal file
View File

@ -0,0 +1,47 @@
#include "work_queue.h"
void queue_init(work_queue *queue) {
queue->head = 0;
queue->tail = 0;
queue->count = 0;
pthread_mutex_init(&queue->lock, NULL);
pthread_cond_init(&queue->not_empty, NULL);
pthread_cond_init(&queue->not_full, NULL);
}
void queue_enqueue(work_queue *queue, work new_work) {
pthread_mutex_lock(&queue->lock);
while (queue->count == QUEUE_SIZE) {
pthread_cond_wait(&queue->not_full, &queue->lock);
}
queue->buffer[queue->tail] = new_work;
queue->tail = (queue->tail + 1) % QUEUE_SIZE;
queue->count++;
pthread_cond_signal(&queue->not_empty);
pthread_mutex_unlock(&queue->lock);
}
work queue_dequeue(work_queue *queue, int *termination_flag) {
pthread_mutex_lock(&queue->lock);
while (queue->count == 0) {
if (*termination_flag) {
pthread_mutex_unlock(&queue->lock);
work empty_work = { 0 };
return empty_work;
}
pthread_cond_wait(&queue->not_empty, &queue->lock);
}
work next_work = queue->buffer[queue->head];
queue->head = (queue->head + 1) % QUEUE_SIZE;
queue->count--;
pthread_cond_signal(&queue->not_full);
pthread_mutex_unlock(&queue->lock);
return next_work;
}

40
main/work_queue.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef WORK_QUEUE_H
#define WORK_QUEUE_H
#include <pthread.h>
#define QUEUE_SIZE 10
#define MAX_MERKLE_BRANCHES 32
#define PREV_BLOCK_HASH_SIZE 32
#define COINBASE_SIZE 100
typedef struct {
uint32_t job_id;
uint8_t prev_block_hash[PREV_BLOCK_HASH_SIZE];
uint8_t coinbase[COINBASE_SIZE];
size_t coinbase_len;
uint8_t merkle_branches[MAX_MERKLE_BRANCHES][PREV_BLOCK_HASH_SIZE];
size_t n_merkle_branches;
uint32_t version;
uint32_t curtime;
uint32_t bits;
uint32_t target;
uint32_t nonce;
} work;
typedef struct {
work buffer[QUEUE_SIZE];
int head;
int tail;
int count;
pthread_mutex_t lock;
pthread_cond_t not_empty;
pthread_cond_t not_full;
} work_queue;
void queue_init(work_queue *queue);
void queue_enqueue(work_queue *queue, work new_work);
work queue_dequeue(work_queue *queue, int *termination_flag);
#endif // WORK_QUEUE_H