From 1b131108dd41115731427650132b7ca3cea0a217 Mon Sep 17 00:00:00 2001 From: orange Date: Thu, 16 May 2013 20:44:46 +0200 Subject: [PATCH] play around with threads --- Makefile | 7 +++++-- threads.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 threads.c diff --git a/Makefile b/Makefile index d23924d..1bf0b0b 100644 --- a/Makefile +++ b/Makefile @@ -2,11 +2,11 @@ CFLAGS=-std=c99 -Wall -g -O2 INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2 .PHONY: all -all: approximate-pi linked-list mandelbrot +all: approximate-pi linked-list mandelbrot threads .PHONY: clean clean: - rm -f approximate-pi linked-list mandelbrot *~ + rm -f approximate-pi linked-list mandelbrot threads *~ .PHONY: indent indent: @@ -14,3 +14,6 @@ indent: mandelbrot: mandelbrot.c $(CC) $(CFLAGS) $(shell sdl-config --cflags) -o $@ $< $(shell sdl-config --libs) -lm + +threads: threads.c + $(CC) $(CFLAGS) -o $@ $< -pthread diff --git a/threads.c b/threads.c new file mode 100644 index 0000000..f7cc32d --- /dev/null +++ b/threads.c @@ -0,0 +1,47 @@ +#include +#include +#include + +#define NUM_THREADS 10 +#define MSG_LEN 100 + +struct thread_data { + char *msg; +}; +typedef struct thread_data thread_data_t; + +void *PrintHello(void *arg) { + thread_data_t *td = (thread_data_t *) arg; + printf("%s", td->msg); + pthread_exit(NULL); +} + +void dienomem() { + printf("ERROR: No memory?!\n"); + exit(1); +} + +int main(int argc, char *argv[]) { + pthread_t threads[NUM_THREADS]; + + for (int t = 0; t < NUM_THREADS; t++) { + /* printf("Creating thread %d\n", t); */ + + thread_data_t *td = malloc(sizeof(thread_data_t)); + if (!td) + dienomem(); + td->msg = malloc(MSG_LEN); + if (!td->msg) + dienomem(); + + snprintf(td->msg, MSG_LEN, "Hello, I'm thread %d!\n", t); + + int rc = pthread_create(&threads[t], NULL, PrintHello, (void *) td); + if (rc) { + printf("ERROR: return code from pthread_create() is %d\n", rc); + exit(1); + } + } + + pthread_exit(NULL); /* Wait for the threads to finish. */ +}