Created
March 22, 2019 07:01
-
-
Save yc0/460bae578d9abaf0c2003b9206278d94 to your computer and use it in GitHub Desktop.
multi-thread sample
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
/** | |
MacOS : clang++ -std=c++17 -stdlib=libc++ -O2 sample.cpp | |
GCC: g++ -std=c++17 -lpthread sample.cpp | |
constrains resource in docker : docker run -it --rm --name=thread --cpuset-cpus="3" gcc bash | |
**/ | |
#include <iostream> | |
#include <sstream> | |
#include <vector> | |
#include <pthread.h> // POSIX | |
#include <sched.h> | |
#include <unistd.h> | |
using namespace std; | |
double pi(uint64_t n) { | |
double sum = 0.0; | |
uint64_t sign = 1; | |
for (uint64_t i = 0; i < n; ++i) { | |
sum += sign/(2.0*i+1.0); | |
sign *= -1; | |
} | |
return 4.0*sum; | |
} | |
// invoke from a thread | |
void* callee(void* m) { | |
string out = static_cast<char *>(m); | |
int num = sysconf(_SC_NPROCESSORS_CONF); | |
printf("system has %d processor(s)\n", num); | |
istringstream iss(out); | |
vector<string> ve; | |
string tmp; | |
while(getline(iss, tmp, ',')) { | |
ve.emplace_back(tmp); | |
} | |
printf("Launch %s by a thread\n", ve[0].c_str()); | |
cout << pi(stoll(ve[1])) << "from " << ve[0] << endl; | |
printf("Done %s by a thread\n", out.c_str()); | |
return nullptr; | |
} | |
int main() { | |
pthread_t t1, t2; | |
pthread_attr_t attr; | |
sched_param param; | |
// sched_priority value in the range 1(low) to 99(high) | |
pthread_attr_init (&attr); | |
pthread_attr_getschedparam (&attr, ¶m); | |
printf("current priority : %d\n", param.sched_priority); | |
param.sched_priority = 99; | |
pthread_attr_setschedparam(&attr, ¶m); | |
pthread_create(&t1, nullptr, callee, (void *) "#1,100000000000"); | |
sleep(3); | |
pthread_create(&t2, &attr, callee, (void *) "#2,10000000"); | |
pthread_join(t1, nullptr); | |
pthread_join(t2, nullptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment