Skip to content

Instantly share code, notes, and snippets.

@1Jo1
Last active August 5, 2020 17:28
Show Gist options
  • Save 1Jo1/6496d1b8b6b363c301271340e2eab95b to your computer and use it in GitHub Desktop.
Save 1Jo1/6496d1b8b6b363c301271340e2eab95b to your computer and use it in GitHub Desktop.
#include <sys/eventfd.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <liburing.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/time.h>
struct io_uring ring;
void error_exit(char *message) {
perror(message);
exit(EXIT_FAILURE);
}
void *listener_thread(void *data) {
struct io_uring_cqe *cqe;
printf("%s: Waiting for completion event...\n", __FUNCTION__);
for(;;) {
int ret = io_uring_wait_cqe(&ring, &cqe);
if (ret < 0) {
fprintf(stderr, "Error waiting for completion: %s\n",
strerror(-ret));
return NULL;
}
if (cqe->res < 0) {
fprintf(stderr, "Error in async operation: %s\n", strerror(-cqe->res));
}
printf("Result of the operation: %d\n", cqe->res);
printf("Result: data: %lld \n", cqe->user_data);
io_uring_cqe_seen(&ring, cqe);
}
return NULL;
}
void *wakeup_io_uring(void *data) {
int efd = (int) data;
printf("efd: %d\n", efd);
int res = eventfd_write(efd, (eventfd_t) 1L);
printf("Write eventfd res: %d \n", res);
return NULL;
}
int setup_io_uring(int efd) {
int ret = io_uring_queue_init(8, &ring, 0);
if (ret) {
fprintf(stderr, "Unable to setup io_uring: %s\n", strerror(-ret));
return 1;
}
return 0;
}
int main() {
pthread_t t1;
pthread_t t2;
int efd;
struct io_uring_sqe *sqe;
efd = eventfd(0, 0);
if (efd < 0) {
error_exit("eventfd");
}
printf("Efd: %d \n", efd);
setup_io_uring(efd);
pthread_create(&t1, NULL, listener_thread, NULL);
sqe = io_uring_get_sqe(&ring);
io_uring_prep_poll_add(sqe, efd, POLLIN);
sqe->user_data = 2;
int ret = io_uring_submit(&ring);
printf("Submit Result: %d\n", ret);
sleep(1);
//io_uring_enter will get a polling event if you move eventfd_write(efd, (eventfd_t) 1L) to the main thread or the other way around
pthread_create(&t2, NULL, wakeup_io_uring, (void *)efd);
pthread_join(t1, NULL);
io_uring_queue_exit(&ring);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment