Merge branch 'master' of luffa:git/c-exercises

master
neingeist 12 years ago
commit fb135c3c42

@ -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

@ -0,0 +1,47 @@
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#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. */
}
Loading…
Cancel
Save