Skip to content

Instantly share code, notes, and snippets.

@vo
Created March 13, 2014 07:24
Show Gist options
  • Save vo/9523308 to your computer and use it in GitHub Desktop.
Save vo/9523308 to your computer and use it in GitHub Desktop.
Stupid simple Pthread example for reference
#include <iostream>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>
typedef struct {
int thread_num;
} data_t;
void *task (void * data) {
data_t * d = (data_t *) data;
for(int i = 0; i < 100; ++i) {
printf("test %d %d\n", d->thread_num, i);
usleep(500000);
}
}
int main () {
pthread_t pool[100];
data_t data[100];
// create 100 threads running the task
for(int i = 0; i < 100; ++i) {
data[i].thread_num = i;
pthread_create(&pool[i], NULL, task, &data[i]);
}
// wait for all the threads to finish
for(int i = 0; i < 100; ++i)
pthread_join(pool[i], NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment