Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Last active November 22, 2021 01:00
Show Gist options
  • Save ProfAvery/84e97e6560eb5ccf29fae8cd554a1bd3 to your computer and use it in GitHub Desktop.
Save ProfAvery/84e97e6560eb5ccf29fae8cd554a1bd3 to your computer and use it in GitHub Desktop.
C++ variant of threads-intro/t1.c (Figure 26.6)
CXXFLAGS = -g -std=c++17 -Wall -Wextra -Wpedantic -Werror -pthread
all: t1 t1-sanitized
# Note: using implicit rule for .cpp files to create t1
t1-sanitized: t1.cpp
$(CXX) $(CXXFLAGS) -o $@ $^ -fsanitize=thread
.PHONY: clean
clean:
rm -f t1 t1-sanitized
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <pthread.h>
using std::cout;
using std::cerr;
using std::endl;
inline int Pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg) {
int rc = pthread_create(thread, attr, start_routine, arg);
assert(rc == 0);
return rc;
}
inline int Pthread_join(pthread_t thread, void **value_ptr) {
int rc = pthread_join(thread, value_ptr);
assert(rc == 0);
return rc;
}
int max;
volatile int counter = 0;
void *mythread(void *arg) {
char *letter = reinterpret_cast<char *>(arg);
int i;
cout << letter << ": begin [addr of i: " << &i << "]" << endl;
for (i = 0; i < max; i++) {
counter = counter + 1;
}
cout << letter << ": done" << endl;
return NULL;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
cerr << "usage: main-first <loopcount>" << endl;
exit(EXIT_FAILURE);
}
max = atoi(argv[1]);
pthread_t p1, p2;
cout << "main: begin [counter = " << counter << "] ["
<< reinterpret_cast<unsigned long int>(&counter) << "]" << endl;
Pthread_create(&p1, NULL, mythread, const_cast<char *>("A"));
Pthread_create(&p2, NULL, mythread, const_cast<char *>("B"));
Pthread_join(p1, NULL);
Pthread_join(p2, NULL);
cout << "main: done\n [counter: " << counter << "]\n [should: "
<< max*2 << "]" << endl;
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment