参考
加入以下语句:
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(1, &mask); 指定该线程使用的CPU
if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
perror("pthread_setaffinity_np");
例子:
#include <stdio.h>
#include <math.h>
// #include <pthread.h>
#include <unistd.h>
#include <sched.h>
#include <thread>
void thread_func1()
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(1, &mask); 指定该线程使用的CPU
if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
perror("pthread_setaffinity_np");
}
///
int count = 0;
while(1)
{
// WasteTime();
count ++;
usleep(100000);
}
}
void thread_func2()
{
int count = 0;
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(2, &mask);
if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
perror("pthread_setaffinity_np");
}
while(1)
{
usleep(10000);
// WasteTime();
count = count*count*count/0.13414 - 2*count;
if (count > 30000)
count = 0;
}
}
int main(int argc, char *argv[])
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(0, &mask);
if (sched_setaffinity(0, sizeof(mask), &mask) < 0) {
perror("sched_setaffinity");
}
std::thread t1(thread_func1);
std::thread t2(thread_func2);
t1.join();
}
// pthread_t my_thread;
// if (pthread_create(&my_thread, NULL, thread_func1,
// NULL) != 0) {
// perror("pthread_create");
// }
// if (pthread_create(&my_thread, NULL, thread_func2,
// NULL) != 0) {
// perror("pthread_create");
// }
// while(1) { WasteTime(); }
// pthread_exit(NULL);
// }
编译
g++ -o test test_thread.cpp -pthread -std=c++11
查看:
ps -ef|grep test_thread
top -p 6024(进程号)
f
光标到P,空格、s、esc
H
对应过程: