Skip to content

Instantly share code, notes, and snippets.

@ryanhs
Created March 17, 2015 08:58
Show Gist options
  • Select an option

  • Save ryanhs/cc5a0747dfcafa31343a to your computer and use it in GitHub Desktop.

Select an option

Save ryanhs/cc5a0747dfcafa31343a to your computer and use it in GitHub Desktop.
multi thread (maybe processor) in c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main() {
long cpu_online = -1;
long cpu_max = -1;
#ifdef _SC_NPROCESSORS_ONLN
cpu_online = sysconf(_SC_NPROCESSORS_ONLN);
if (cpu_online < 1)
{
fprintf(stderr, "hmm somethings wrong! debug:cpu_online");
return 1;
}
cpu_max = sysconf(_SC_NPROCESSORS_CONF);
if (cpu_max < 1)
{
fprintf(stderr, "hmm somethings wrong! debug:cpu_max");
return 1;
}
printf ("%ld of %ld processors online\n", cpu_online, cpu_max);
return main_threaded(cpu_online);
#else
fprintf(stderr, "hmm somethings wrong!");
return 1;
#endif
}
typedef struct {
int thread_id;
pthread_t thread;
} workerStruct;
void *worker(void *param)
{
workerStruct *me = (workerStruct *) param;
printf("worker #%d started! \n", me->thread_id);
int i = 0;
while(1) i++;
return NULL;
}
int main_threaded(max_worker){
// test half processors
// max_worker = max_worker / 2;
int i = 0;
workerStruct workers[4];
for(; i < max_worker; i++){
workers[i].thread_id = i;
pthread_create(&workers[i].thread, NULL, worker, &workers[i]);
}
for(i = 0; i < max_worker; i++){
pthread_join(workers[i].thread, NULL);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment