Created
February 13, 2021 05:11
-
-
Save mrryanjohnston/67ddb82b3ea7324432bc6617a307f67a to your computer and use it in GitHub Desktop.
Learning C: pthread and mqueue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <mqueue.h> | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <unistd.h> | |
const char *QUEUE_NAME = "/foo"; | |
const char *MESSAGE = "hi\n"; | |
void *one(void *arg) { | |
pthread_detach(pthread_self()); | |
mqd_t mqd = mq_open(QUEUE_NAME, O_WRONLY); | |
int *seconds = (int *)arg; | |
mq_send(mqd, "asdf\n", strlen("asdf\n") + 1, 1); | |
printf("DEBUG: Thread %ld sleeping for %d seeconds...\n", pthread_self(), *seconds); | |
sleep(*seconds); | |
printf("DEBUG: Thread %ld woke up after %d seconds!!\n", pthread_self(), *seconds); | |
mq_send(mqd, MESSAGE, strlen(MESSAGE) + 1, 1); | |
} | |
int main() { | |
struct mq_attr attr; | |
attr.mq_flags = 0; | |
attr.mq_maxmsg = 10; | |
attr.mq_msgsize = 33; | |
attr.mq_curmsgs = 0; | |
mqd_t mqd = mq_open(QUEUE_NAME, O_CREAT | O_RDWR, 0644, &attr); | |
if (mqd == -1) { | |
char *error; | |
sprintf(error, "ERROR: queue %s", QUEUE_NAME); | |
perror(error); | |
return 1; | |
} | |
printf("DEBUG: file descriptor: %d\n", mqd); | |
pthread_t ptid; | |
int second1, second2, second3; | |
second3 = 3; | |
if (pthread_create(&ptid, NULL, one, &second3)) { | |
perror("ERROR: could not start thread\n"); | |
return 1; | |
} | |
printf("DEBUG: Created thread %ld\n", ptid); | |
second1 = 1; | |
if (pthread_create(&ptid, NULL, one, &second1)) { | |
perror("ERROR: could not start thread\n"); | |
return 1; | |
} | |
printf("DEBUG: Created thread %ld\n", ptid); | |
second2 = 2; | |
if (pthread_create(&ptid, NULL, one, &second2)) { | |
perror("ERROR: could not start thread\n"); | |
return 1; | |
} | |
printf("DEBUG: Created thread %ld\n", ptid); | |
char msg_ptr[1000000]; | |
int should = 0; | |
while(should < 6) { | |
if (mq_receive(mqd, msg_ptr, 1000000, NULL) != -1) { | |
printf("DEBUG: Message from thread: %s\n", msg_ptr); | |
should++; | |
} | |
} | |
mq_close(mqd); | |
mq_unlink(QUEUE_NAME); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
all: | |
gcc main.c -lpthread -lrt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment