Skip to content

Instantly share code, notes, and snippets.

@ProfAvery
Created September 22, 2020 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ProfAvery/d027e9ab1d1655249f6a39882c67afe5 to your computer and use it in GitHub Desktop.
Save ProfAvery/d027e9ab1d1655249f6a39882c67afe5 to your computer and use it in GitHub Desktop.
C++ variant of Figure 4.11
#include <cstdlib>
#include <iostream>
#include <pthread.h>
using std::cout;
using std::cerr;
using std::endl;
// Don't forget to compile with -pthread
int sum = 0;
void *runner(void *param);
int main(int argc, char *argv[])
{
if (argc != 2) {
cerr << "Usage: " << argv[0] << " N" << endl;
return EXIT_FAILURE;
}
pthread_t tid;
errno = pthread_create(&tid, NULL, runner, argv[1]);
if (errno != 0) {
perror("pthread_create");
return EXIT_FAILURE;
}
errno = pthread_join(tid, NULL);
if (errno != 0) {
perror("pthread_join");
return EXIT_FAILURE;
}
cout << "sum = " << sum << endl;
return EXIT_SUCCESS;
}
void *runner(void *param)
{
char *s = reinterpret_cast<char *>(param);
auto upper = atoi(s);
for (auto i = 1; i < upper; i++) {
sum += i;
}
pthread_exit(NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment