Skip to content

Instantly share code, notes, and snippets.

@AlmuHS
Last active October 8, 2023 21:33
Show Gist options
  • Save AlmuHS/69fe3962cbe637c3d47f7ed7b7340139 to your computer and use it in GitHub Desktop.
Save AlmuHS/69fe3962cbe637c3d47f7ed7b7340139 to your computer and use it in GitHub Desktop.
SMP Demo Code: Execute a bunch of threads, showing by screen which cpu are executing each - 32-bit version
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#define MS_STOP_TIME 100
#define NUM_THREADS 16
unsigned int get_apic_id(void){
unsigned int cpu_eax, cpu_ebx, cpu_ecx, cpu_edx;
cpu_eax = 0x1;
asm (
"mov %%eax, %0\n\t"
"cpuid\n\t"
"mov %0, %%eax\n\t"
"mov %1, %%ebx\n\t"
"mov %2, %%ecx\n\t"
"mov %3, %%edx\n\t"
: "=r" (cpu_eax), "=r" (cpu_ebx), "=r" (cpu_ecx), "=r" (cpu_edx)
: "0" (cpu_eax)
);
unsigned int apic_id = cpu_ebx >> 24;
return apic_id;
}
void *thread_routine()
{
while(1){
unsigned int apic_id = get_apic_id();
printf ("Thread %u - %x\n",pthread_self(), apic_id);
volatile int time = 0, time2;
while(time < MS_STOP_TIME*100000){
time++;
time2 = time+1;
}
}
}
int main()
{
pthread_t threads[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++){
pthread_create(&threads[i],NULL,(void *) &thread_routine, NULL);
}
for(int i = 0; i < NUM_THREADS; i++){
pthread_join(threads[i],NULL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment