some thread API examples

This commit is contained in:
Remzi Arpaci-Dusseau
2019-04-23 12:12:17 -05:00
parent b4fa80ad67
commit 502a67f965
5 changed files with 121 additions and 0 deletions

21
threads-api/Makefile Normal file
View File

@@ -0,0 +1,21 @@
CC := gcc
CFLAGS := -Wall -Werror -I../include
SRCS := thread_create.c \
thread_create_simple_args.c \
thread_create_with_return_args.c
OBJS := ${SRCS:c=o}
PROGS := ${SRCS:.c=}
.PHONY: all
all: ${PROGS}
${PROGS} : % : %.o Makefile
${CC} $< -o $@ -pthread
clean:
rm -f ${PROGS} ${OBJS}
%.o: %.c Makefile
${CC} ${CFLAGS} -c $<

20
threads-api/README.md Normal file
View File

@@ -0,0 +1,20 @@
# Threads API
Some simple examples of how to use POSIX thread APIs.
Relevant files:
- `thread_create.c`: A simple thread creation program, with args passed to the
thread.
- `thread_create_with_return_args.c`: Return values from the thread to the
parent.
- `thread_create_simple_args.c`: Simpler argument/return value passing for the
lazy.
Type `make` to build; each file `foo.c` generates an executable `foo` which
you can then run, e.g.:
```sh
prompt> ./thread_create
```

View File

@@ -0,0 +1,25 @@
#include <assert.h>
#include <stdio.h>
#include <pthread.h>
typedef struct {
int a;
int b;
} myarg_t;
void *mythread(void *arg) {
myarg_t *args = (myarg_t *) arg;
printf("%d %d\n", args->a, args->b);
return NULL;
}
int main(int argc, char *argv[]) {
pthread_t p;
myarg_t args = { 10, 20 };
int rc = pthread_create(&p, NULL, mythread, &args);
assert(rc == 0);
(void) pthread_join(p, NULL);
printf("done\n");
return 0;
}

View File

@@ -0,0 +1,19 @@
#include <stdio.h>
#include <pthread.h>
#include "common_threads.h"
void *mythread(void *arg) {
long long int value = (long long int) arg;
printf("%lld\n", value);
return (void *) (value + 1);
}
int main(int argc, char *argv[]) {
pthread_t p;
long long int rvalue;
Pthread_create(&p, NULL, mythread, (void *) 100);
Pthread_join(p, (void **) &rvalue);
printf("returned %lld\n", rvalue);
return 0;
}

View File

@@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "common_threads.h"
typedef struct {
int a;
int b;
} myarg_t;
typedef struct {
int x;
int y;
} myret_t;
void *mythread(void *arg) {
myarg_t *args = (myarg_t *) arg;
printf("args %d %d\n", args->a, args->b);
myret_t *rvals = malloc(sizeof(myret_t));
assert(rvals != NULL);
rvals->x = 1;
rvals->y = 2;
return (void *) rvals;
}
int main(int argc, char *argv[]) {
pthread_t p;
myret_t *rvals;
myarg_t args = { 10, 20 };
Pthread_create(&p, NULL, mythread, &args);
Pthread_join(p, (void **) &rvals);
printf("returned %d %d\n", rvals->x, rvals->y);
free(rvals);
return 0;
}