Created
September 22, 2020 23:24
-
-
Save ProfAvery/d027e9ab1d1655249f6a39882c67afe5 to your computer and use it in GitHub Desktop.
C++ variant of Figure 4.11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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