博客:blog.focus-linux.net linuxfocus.blog.chinaunix.net
-
#define _GNU_SOURCE
-
#include <pthread.h>
-
#include <sched.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <errno.h>
-
#include <sys/types.h>
-
#include <unistd.h>
-
- // 設置線程的CPU親和性,使不同線程同時運行在不同的CPU上
-
static int set_thread_affinity(int cpu_id)
-
{
-
cpu_set_t cpuset;
- int ret;
-
-
CPU_ZERO(&cpuset);
-
CPU_SET(cpu_id, &cpuset);
-
-
ret = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
-
if (ret != 0) {
-
printf("set affinity error\n");
-
return -1;
-
}
-
-
return 0;
-
}
-
static void check_cpu_affinity(void)
-
{
-
cpu_set_t cpu_set;
-
int ret;
-
int i;
-
-
ret = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu_set);
-
if (ret != 0) {
-
printf("check err!\n");
-
return;
-
}
-
-
for (i = 0; i < CPU_SETSIZE; ++i) {
-
if (CPU_ISSET(i, &cpu_set)) {
-
printf("cpu %d\n", i);
-
}
-
}
-
-
}
-
-
-
#define CPU_NR 2
-
#define CACHE_LINE_SIZE 64
-
#define VAR_NR ((CACHE_LINE_SIZE/sizeof(int))-1)
- //這個結構爲多核編程中最頻繁使用的結構
- //其size大小爲本文重點
-
struct key {
-
int a[VAR_NR];
-
//int pad;
-
} __attribute__((packed));
- //使用空間換時間,每個CPU擁有不同的數據
-
static struct key g_key[CPU_NR];
-
static void real_job(int index)
-
{
-
#define LOOP_NR 100000000
-
struct key *k = g_key+index;
-
-
int i;
-
for (i = 0; i < VAR_NR; ++i) {
-
k->a[i] = i;
-
}
-
-
for (i = 0; i < LOOP_NR; ++i) {
-
k->a[14] = k->a[14]+k->a[3];
-
k->a[3] = k->a[14]+k->a[5];
-
k->a[1] = k->a[1]+k->a[7];
-
k->a[7] = k->a[1]+k->a[9];
-
}
-
}
-
-
static volatile int thread_ready = 0;
-
static void *thread_task(void *data)
-
{
-
set_thread_affinity(1);
-
check_cpu_affinity();
-
-
thread_ready = 1;
-
-
real_job(1);
-
-
return NULL;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
pthread_t tid;
-
int ret;
-
ret = set_thread_affinity(0);
-
if (ret != 0) {
-
printf("err1\n");
-
return -1;
-
}
-
check_cpu_affinity();
-
ret = nice(-20);
-
if (-1 == ret) {
-
printf("err2\n");
-
return -1;
-
}
-
-
ret = pthread_create(&tid, NULL, thread_task, NULL);
-
if (ret != 0) {
-
printf("err2\n");
-
return -1;
-
}
-
while (!thread_ready)
-
;
-
-
real_job(0);
-
-
pthread_join(tid, NULL);
-
-
printf("Completed!\n");
-
-
return 0;
- }
- [root@Lnx99 cache]#gcc -g -Wall cache_line.c -lpthread -o no_padd
- [root@Lnx99 cache]#time ./no_padd
- cpu 0
- cpu 1
- Completed!
- real 0m9.830s
- user 0m19.427s
- sys 0m0.011s
- [root@Lnx99 cache]#time ./no_padd
- cpu 0
- cpu 1
- Completed!
- real 0m10.081s
- user 0m20.074s
- sys 0m0.010s
- [root@Lnx99 cache]#time ./no_padd
- cpu 0
- cpu 1
- Completed!
- real 0m9.989s
- user 0m19.877s
- sys 0m0.010s
- [root@Lnx99 cache]#gcc -g -Wall cache_line.c -lpthread -o padd
- [root@Lnx99 cache]#time ./padd
- cpu 0
- cpu 1
- Completed!
- real 0m1.824s
- user 0m3.614s
- sys 0m0.012s
- [root@Lnx99 cache]#time ./padd
- cpu 0
- cpu 1
- Completed!
- real 0m1.817s
- user 0m3.625s
- sys 0m0.011s
- [root@Lnx99 cache]#time ./padd
- cpu 0
- cpu 1
- Completed!
- real 0m1.824s
- user 0m3.613s
- sys 0m0.011s