Skip to content

Instantly share code, notes, and snippets.

@yc0
Created March 22, 2019 07:01
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 yc0/460bae578d9abaf0c2003b9206278d94 to your computer and use it in GitHub Desktop.
Save yc0/460bae578d9abaf0c2003b9206278d94 to your computer and use it in GitHub Desktop.
multi-thread sample
/**
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, &param);
printf("current priority : %d\n", param.sched_priority);
param.sched_priority = 99;
pthread_attr_setschedparam(&attr, &param);
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