play around with threads
This commit is contained in:
parent
b12b4ff429
commit
1b131108dd
2 changed files with 52 additions and 2 deletions
7
Makefile
7
Makefile
|
@ -2,11 +2,11 @@ CFLAGS=-std=c99 -Wall -g -O2
|
||||||
INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2
|
INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2
|
||||||
|
|
||||||
.PHONY: all
|
.PHONY: all
|
||||||
all: approximate-pi linked-list mandelbrot
|
all: approximate-pi linked-list mandelbrot threads
|
||||||
|
|
||||||
.PHONY: clean
|
.PHONY: clean
|
||||||
clean:
|
clean:
|
||||||
rm -f approximate-pi linked-list mandelbrot *~
|
rm -f approximate-pi linked-list mandelbrot threads *~
|
||||||
|
|
||||||
.PHONY: indent
|
.PHONY: indent
|
||||||
indent:
|
indent:
|
||||||
|
@ -14,3 +14,6 @@ indent:
|
||||||
|
|
||||||
mandelbrot: mandelbrot.c
|
mandelbrot: mandelbrot.c
|
||||||
$(CC) $(CFLAGS) $(shell sdl-config --cflags) -o $@ $< $(shell sdl-config --libs) -lm
|
$(CC) $(CFLAGS) $(shell sdl-config --cflags) -o $@ $< $(shell sdl-config --libs) -lm
|
||||||
|
|
||||||
|
threads: threads.c
|
||||||
|
$(CC) $(CFLAGS) -o $@ $< -pthread
|
||||||
|
|
47
threads.c
Normal file
47
threads.c
Normal file
|
@ -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…
Add table
Add a link
Reference in a new issue