Untitled

 avatar
unknown
plain_text
19 days ago
1.3 kB
3
Indexable
#include <iostream>
#include <thread>
#include <vector>
#include <sched.h>  // For sched_getcpu()
#include <pthread.h> // For pthread_setaffinity_np

void set_thread_affinity(std::thread& t, int core_id) {
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(core_id, &cpuset);

    int rc = pthread_setaffinity_np(t.native_handle(), sizeof(cpu_set_t), &cpuset);
    if (rc != 0) {
        std::cerr << "Error setting thread affinity: " << rc << std::endl;
    }
}

void function1() {
    for (int i = 0; i < 200; i++) {
        std::cout << "+";
    }
    std::cout << "\nThread 1 is running on core: " << sched_getcpu() << std::endl;
}

void function2() {
    for (int i = 0; i < 200; i++) {
        std::cout << "-";
    }
    std::cout << "\nThread 2 is running on core: " << sched_getcpu() << std::endl;
}

int main() {
    std::thread t1(function1);
    std::thread t2(function2);

    // Bind both threads to core 0
    set_thread_affinity(t1, 0);
    set_thread_affinity(t2, 0);

    std::thread::id t1_id = t1.get_id();
    std::thread::id t2_id = t2.get_id();

    std::cout << "ID of thread 1: " << t1_id << std::endl;
    std::cout << "ID of thread 2: " << t2_id << std::endl;

    t1.join();
    t2.join();

    return 0;
}
Editor is loading...
Leave a Comment