Added common include for simple C programs, and threads-intro code
This commit is contained in:
14
threads-intro/Makefile
Normal file
14
threads-intro/Makefile
Normal file
@@ -0,0 +1,14 @@
|
||||
|
||||
FLAGS = -Wall -pthread
|
||||
INCLUDES = ../include
|
||||
|
||||
all: t0 t1
|
||||
|
||||
clean:
|
||||
rm -f t0 t1
|
||||
|
||||
t0: t0.c
|
||||
gcc -I $(INCLUDES) -o t0 t0.c $(FLAGS)
|
||||
|
||||
t1: t1.c
|
||||
gcc -I $(INCLUDES) -o t1 t1.c $(FLAGS)
|
||||
28
threads-intro/t0.c
Normal file
28
threads-intro/t0.c
Normal file
@@ -0,0 +1,28 @@
|
||||
#include "common.h"
|
||||
#include "common_threads.h"
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
void *mythread(void *arg) {
|
||||
printf("%s\n", (char *) arg);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 1) {
|
||||
fprintf(stderr, "usage: main\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
pthread_t p1, p2;
|
||||
printf("main: begin\n");
|
||||
Pthread_create(&p1, NULL, mythread, "A");
|
||||
Pthread_create(&p2, NULL, mythread, "B");
|
||||
// join waits for the threads to finish
|
||||
Pthread_join(p1, NULL);
|
||||
Pthread_join(p2, NULL);
|
||||
printf("main: end\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
40
threads-intro/t1.c
Normal file
40
threads-intro/t1.c
Normal file
@@ -0,0 +1,40 @@
|
||||
#include "common.h"
|
||||
#include "common_threads.h"
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int max;
|
||||
volatile int counter = 0; // shared global variable
|
||||
|
||||
void *mythread(void *arg) {
|
||||
char *letter = arg;
|
||||
int i; // stack (private per thread)
|
||||
printf("%s: begin [addr of i: %p]\n", letter, &i);
|
||||
for (i = 0; i < max; i++) {
|
||||
counter = counter + 1; // shared: only one
|
||||
}
|
||||
printf("%s: done\n", letter);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc != 2) {
|
||||
fprintf(stderr, "usage: main-first <loopcount>\n");
|
||||
exit(1);
|
||||
}
|
||||
max = atoi(argv[1]);
|
||||
|
||||
pthread_t p1, p2;
|
||||
printf("main: begin [counter = %d] [%x]\n", counter,
|
||||
(unsigned int) &counter);
|
||||
Pthread_create(&p1, NULL, mythread, "A");
|
||||
Pthread_create(&p2, NULL, mythread, "B");
|
||||
// join waits for the threads to finish
|
||||
Pthread_join(p1, NULL);
|
||||
Pthread_join(p2, NULL);
|
||||
printf("main: done\n [counter: %d]\n [should: %d]\n",
|
||||
counter, max*2);
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user