Skip to content

Instantly share code, notes, and snippets.

@jpustula
Last active August 29, 2015 13:58
Show Gist options
  • Save jpustula/10011294 to your computer and use it in GitHub Desktop.
Save jpustula/10011294 to your computer and use it in GitHub Desktop.
/*
* Przykładowy program rozdzielający wątki na konkretne rdzenie.
*
* Kompilacja:
* g++ thread_affinity.cpp -o thread_affinity -lpthread -std=c++11
*
* Oparte na przykładzie:
* http://stackoverflow.com/questions/1407786/how-to-set-cpu-affinity-of-a-particular-pthread
*
* Dokumentacja:
* http://www.gnu.org/software/libc/manual/html_node/CPU-Affinity.html
*/
#include <iostream>
#include <thread>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
using std::cin;
using std::cout;
using std::thread;
void print_cpu_details()
{
int total_cpu_cores = sysconf(_SC_NPROCESSORS_ONLN);
cout << "# Liczba rdzeni: " << total_cpu_cores << "\n";
}
/**
* Przydziela wątek do konkretnego rdzenia, podanego jako argument.
* Rdzenie numerowane są od zera. Najlepiej wywoływać na początku wątku.
*
* @param core_id Numer rdzenia, do którego przypisany ma być wątek
*/
int set_thread_affinity(int core_id)
{
int total_cpu_cores = sysconf(_SC_NPROCESSORS_ONLN);
// Nieprawidłowy argument
if (core_id < 0 || core_id >= total_cpu_cores)
{
return EINVAL;
}
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_t current_thread = pthread_self();
return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);
}
void test_thread(int core_id)
{
int core = set_thread_affinity(core_id);
int result = 0;
double time = 10000000000;
cout << "# Numer obciążanego rdzenia: " << core_id << "\n";
// Bezsensowna pętla do obciążenia rdzenia przez pewien czas
while (time--)
{
result = 99999 + 9.086538739;
}
}
int main()
{
char option;
// Wyświetla podstawowe informacje o procesorze
print_cpu_details();
do
{
cout << "Podaj numer rdzenia do obciazenia:\n";
cin >> option;
if (option != 'q')
{
thread t(test_thread, option - 48);
t.join();
}
}
while (option != 'q');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment